2013-04-17 33 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不一样,因为后者指的是进程句柄而不是窗口句柄。

相关问题