function x1(P: Pointer): LongInt; stdcall;
begin
SendMessage(Form1.Handle, WM_username, Integer(PChar('线程1:' + getname)), 0);
end
function x2(P: Pointer): LongInt; stdcall;
begin
SendMessage(Form1.Handle, WM_username, Integer(PChar('线程2:' + getname)), 0);
end
function x3(P: Pointer): LongInt; stdcall;
begin
SendMessage(Form1.Handle, WM_username, Integer(PChar('线程3:' + getname)), 0);
end
procedure TForm1.bsSkinButton1Click(Sender: TObject);
var
  getlink: TMyThread;
  hThread: THandle;
  ThreadID: DWord;
    hThread1: THandle;
  ThreadID1: DWord;
      hThread2: THandle;
  ThreadID2: DWord;
begin  hthread :=beginThread(nil, //Security attribute
    0, //Initial Stack
    @x1, //Starting address of thread
    nil, // argument of thread
    0, // Create flags
    ThreadID); // thread ID
 // hthread1 := CreateThread (nil, //Security attribute
  hthread1 :=beginThread(nil, //Security attribute
    0, //Initial Stack
    @x2, //Starting address of thread
    nil, // argument of thread
    0, // Create flags
    ThreadID1); // thread ID
      hthread2 :=beginThread(nil, //Security attribute
    0, //Initial Stack
    @x3, //Starting address of thread
    nil, // argument of thread
    0, // Create flags
    ThreadID2); // thread IDend;我现在这样启动3个线程 ,并用SendMessage(Form1.Handle, WM_username, Integer(PChar('线程1:' + getname)), 0);让窗体响应消息,好识别是哪个线程发送过来的消息,现在的问题是X1,X2,X3的函数内容是一样的,重复写代码有点麻烦, 并且我要是需要创建几十个线程,那就要写几十个函数了,所以来请教兄弟们了

解决方案 »

  1.   


    const
      WM_TEST = WM_USER + 1000;function ThreadProc(P: Pointer): DWORD; stdcall;
    begin
      SendMessage(Form1.Handle, WM_TEST, 0, LongInt(PChar('线程' + IntToStr(Integer(P)) + 'Test')));
      Result := 0;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      ThreadId: DWORD;
      I: Integer;
    begin
      for I := 0 to 32 do
        CloseHandle(CreateThread(nil, 0, @ThreadProc, Pointer(I), 0, ThreadId));
    end;procedure TForm1.WMTEST(var Msg: TMsg);
    begin
      Memo1.Lines.Add(PChar(Msg.wParam));
    end;
      

  2.   

    CloseHandle(CreateThread是什么意思,创建了关闭,还是等CreateThread创建的函数执行完毕了关闭线程
      

  3.   

    要是用不到线程的 handle 的话(比如不需要暂停或恢复等),线程运行起来了就 CloseHandle 也没问题