2013-04-17 42 views
1

我有一個WinForms,Application.Run之前(新Form1的())我發送消息給其他應用程序WinForms:有沒有辦法在Application.Run(新的Form1())之前獲得窗口句柄?

[DllImport("user32.dll")] 
public static extern long SendMessage(IntPtr Handle, int Msg, int wParam, int lParam); 

,但我不能讓窗口的句柄,我想:

IntPtr Handle = Process.GetCurrentProcess().Handle; 

但有時它會返回錯誤的句柄。
我該怎麼做?非常感謝你!

回答

1

SendMessage函數的第一個參數是將接收消息的窗口的句柄。 Process.GetCurrentProcess().Handle返回當前進程的本地句柄。這不是一個窗口句柄。

Application.Run啓動應用程序的消息循環。 由於您想將消息發送到另一個應用程序,因此您的應用程序根本不需要消息循環。但是,您需要處理其他應用程序的窗口。

以下示例顯示瞭如何使用SendMessage關閉另一個應用程序的主窗口:

[DllImport("user32.dll")] 
public static extern long SendMessage(IntPtr Handle, int Msg, int wParam, int lParam); 

public const int WM_CLOSE = 0x0010; 

private static void Main() 
{ 
    var processes = Process.GetProcessesByName("OtherApp"); 
    if (processes.Length > 0) 
    { 
     IntPtr handle = processes[0].MainWindowHandle; 
     SendMessage(handle, WM_CLOSE, 0, 0); 
    } 
} 
1

如果你想將消息發送到不同應用程序,那麼你需要得到窗口句柄,而不是屬於自己的進程的窗口句柄。使用Process.GetProcessesByName查找特定的進程,然後使用MainWindowHandle屬性獲取窗口句柄。請注意0​​與Handle不一樣,因爲後者指的是進程句柄而不是窗口句柄。

相關問題