2011-08-01 39 views
6

的目標是創建兩個線程,其中一個是主線程之間的通信。我正在尋找的是創建一個佔用較少資源並僅用於接收消息的窗口。如何創建一個純粹的WINAPI窗口

還有什麼你是指我?

+2

您可能想看看['AllocateHWnd'](http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Classes_AllocateHWnd.html)。 –

+0

@Sertac Akyuz,對不起,我無意中劫持了你的建議,只是在寫下我自己的回答後才注意到它:-( –

+0

AndocateHwnd的缺點是它不是線程安全的。當然,這可以解決。 –

回答

7

你需要做的是建立在你的線程的消息循環,並使用AllocateHWnd在你的主線程向後和向前發送消息。這很簡單。

在你的線程中執行功能有以下幾點:

procedure TMyThread.Execute; 
begin 
    // this sets up the thread message loop 
    PeekMessage(LMessage, 0, WM_USER, WM_USER, PM_NOREMOVE); 

    // your main loop 
    while not terminated do 
    begin 
    // look for messages in the threads message queue and process them in turn. 
    // You can use GetMessage here instead and it will block waiting for messages 
    // which is good if you don't have anything else to do in your thread. 
    while PeekMessage(LMessage, 0, WM_USER, $7FFF, PM_REMOVE) do 
    begin 
     case LMessage.Msg of 
     //process the messages 
     end; 
    end; 

    // do other things. There would probably be a wait of some 
    // kind in here. I'm just putting a Sleep call for brevity 
    Sleep(500); 

    end; 
end; 

要發送消息給你的線程,這樣做如下:

PostThreadMessage(MyThread.Handle, WM_USER, 0, 0); 

對事物的主線程側,設置使用AllocateHWnd(在Classes中)傳遞一個WndProc方法。 AllocateHWnd是非常輕便,使用簡單:

TMyMessageReciever = class 
private 
    FHandle: integer; 

    procedure WndProc(var Msg: TMessage); 

public 
    constructor Create; 
    drestructor Destroy; override; 

    property Handle: integer read FHandle; 

end; 

implementation 

constructor TMyMessageReciever.Create; 
begin 
    inherited Create; 
    FHandle := Classes.AllocateHWnd(WndProc); 
end; 

destructor TMyMessageReciever.Destroy; 
begin 
    DeallocateHWnd(FHandle); 
    inherited Destroy; 
end; 

procedure TMyMessageReciever.WndProc(var Msg: TMessage); 
begin 
    case Msg.Msg of 
    //handle your messages here 
    end; 
end; 

,並用SendMessage發送消息,這將阻止,直到該消息已被處理,或PostMessage這確實是異步。

希望這會有所幫助。

+3

或者,你並不真的需要'AllocateHwnd()'上主線程,特別是如果你想減少資源。使用'PostThreadMessage()'使用'MainThreadID'變量作爲目標線程ID將消息直接發送到主線程消息隊列,然後使用'TApplication.OnMessage'事件接收消息。您可以通過查看TMsg.hwnd成員來區分窗口消息中的線程消息,該消息對於線程消息將爲零。 –

+0

試了兩個,但沒有一個在控制檯應用上工作。我的代碼 - > http://pastebin.com/jm5K4EHN – netboy

+0

我沒有意識到你是在一個控制檯應用程序中...我看到你的代碼中的問題...你沒有定期檢查消息隊列以查看如果有任何消息......你的代碼只是坐在Readln上。對於「非控制檯」應用程序,您需要定期調用Application.Process消息。在控制檯版本中,您需要一個消息泵。我認爲你應該看看安德烈亞斯的榜樣,這正是你想要做的。 – Nat

7

這是message-only windows是。我在a previous question上寫了一個Delphi發送+接收系統示例。

+0

類品牌的這個問題是一個愚蠢的問題,除了鏈接的問題是如此具體,而且這個問題是一般性的,因此這個問題更有用。也許在這種情況下,最好只粘貼整個代碼示例(複製它)在這裏。 。您的想法? –

2

Gabr的OmniThread Library提供了一個很好的小單元DSiWin32,用它來創建消息窗口,或者您可以使用OmniThread爲您進行通信。

+0

這是優於做兩輪牛車水平低一點。 –

相關問題