0

So when I cannot figure out why my PostMessage is not working. Here is what I have.

[DllImport("user32.dll")]
        static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

private void Send_Click(object sender, EventArgs e)
        {
            uint WM_KEYDOWN = 0x0100;
            Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
            IntPtr h = p.MainWindowHandle;
            PostMessage(h,
               WM_KEYDOWN,
               (int)Keys.D, 0);
        }

The above code doesn't work at all. Oddly enough though the below code does. Why doesn't postmessage work? I am on Windows 8 if thats any help.

[DllImport("user32.dll")]
        static extern int SetForegroundWindow(IntPtr point);

private void SendUp_Click(object sender, EventArgs e)
        {
            Process p = Process.GetProcessesByName("notepad").FirstOrDefault();

            if (p != null)
            {
                IntPtr h = p.MainWindowHandle;
                SetForegroundWindow(h);

                    SendKeys.Send("D");
            }
        }
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • Use `SendKey` instead: [C# using Sendkey function to send a key to another application](http://stackoverflow.com/q/15292175/1768303). – noseratio Feb 15 '14 at 08:47
  • I am already doing what is described there. I am curious though why the first block of code I have isn't working. – allencoded Feb 15 '14 at 08:51
  • It is because you are posting the message to the wrong window. The main window of Notepad is *not* the window that contains the editor. It is the frame around the editor. Use Spy++ to see there's more than one. EnumChildWindows() to find it. – Hans Passant Feb 15 '14 at 09:53

0 Answers0