Reputation: 8025
I have a winforms, before Application.Run(new Form1()) I send message to other app
[DllImport("user32.dll")]
public static extern long SendMessage(IntPtr Handle, int Msg, int wParam, int lParam);
but I cannot get window handle, I tried:
IntPtr Handle = Process.GetCurrentProcess().Handle;
but sometime it returm wrong handle.
How can I do this? Thank you very much!
Upvotes: 1
Views: 1487
Reputation: 3123
The first argument of the SendMessage
function is the handle of the window that will receive the message.
Process.GetCurrentProcess().Handle
returns the native handle of the current process. That's not a window handle.
Application.Run
starts the message loop for the application.
Since you want to send a message to another application your application doesn't need a message loop at all. You need however the handle to the other application's window.
The following example shows how to close the main window of another app using 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);
}
}
Upvotes: 1
Reputation: 3821
If you're trying to send a message to a different application then you need to get its window handle instead of the window handle belonging to your own process. Use Process.GetProcessesByName
to find a specific process, and then use the MainWindowHandle
property to get the window handle. Note that MainWindowHandle
is not the same as Handle
, as the latter refers to the process handle rather than the window handle.
Upvotes: 1