I can't understand how to use SendMessage or PostMessage calls

Joao Oliveira picture Joao Oliveira · Apr 30, 2009 · Viewed 42.4k times · Source

I need to simulate a keypress in a third party application. Let's say I have a C# application that needs to send an "8" to the Calculator application. I can't use the SendKeys of .Net or the keybd_event of win32 api because they both require the window to be the top active one, which is not case in my situation.

So that leaves me with the calls sendMessage and postMessage. I've been trying in the last three hours trying to get some results but right now I'm completely hopeless.

I have the following:

        [DllImport("user32.dll")]
    public static extern int FindWindow(string lpClassName,string lpWindowName);
    [DllImport("user32.dll")]
    public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool PostMessage(int hWnd, uint Msg, int wParam, int lParam);

    private void button1_Click(object sender, EventArgs e)
    {
        const int WM_KEYDOWN = 0x100;
        const int WM_SYSCOMMAND = 0x018;
        const int SC_CLOSE = 0x053;

        int WindowToFind = FindWindow(null,"Calculator");

        int result = SendMessage(WindowToFind, WM_SYSCOMMAND, SC_CLOSE, 0);
        Boolean result2 = PostMessage(WindowToFind, WM_SYSCOMMAND, SC_CLOSE, 0);

        int result3 = SendMessage(WindowToFind, WM_KEYDOWN,((int)Keys.NumPad7), 0);
        Boolean result4 = PostMessage(WindowToFind, WM_KEYDOWN, ((int)Keys.NumPad7), 0);
    }

As you can see, I make four attempts to communicate with the Calculator. Using both sendMessage and PostMessage to close the window and also to send the key 7. Nothing works. The FindWindow Method works cause I get the handler of the app (I've even tryed launching the process myself and accessing it with process.MainWindowHandler, but no luck). There are no errors or exceptions, but it just doesn't do nothing in Calculator.

I've also tried the exact same things with notepad and nothing changed too.

Answer

Jonathan Rupp picture Jonathan Rupp · Apr 30, 2009

Any chance you're running this on a 64bit machine? If so, I believe all those 'int' values that are actually hWnds (first argument to Send/Post, return value from FindWindow) need to be IntPtr.


After a bit more checking, it looks like for both SendMessage and PostMessage, the 1st, 3rd, and 4th parameters should be IntPtr instead of int (as well as the return values for all of these)

So, the right signatures would be:

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);