Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send Enter key with PostMessage in C#?

I'm trying to send some input to a window with PostMessage. I'm not using SendInput because it won't be in focus. I've got characters (A) being entered but how do I send the Enter key? This is the cut down version of my code. Its runs but Enter is not sent?

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

const int WM_KEYDOWN    = 0x100;
const int WM_KEYUP      = 0x101;

const Int32 WM_CHAR = 0x0102;
const Int32 VK_RETURN = 0x0D;
const int VK_ENTER = 0x0D;

IntPtr val = new IntPtr((Int32)'A');
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_CHAR, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, VK_RETURN, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));
like image 915
Mr J Avatar asked Oct 16 '25 20:10

Mr J


1 Answers

I think you're sending the enter wrong. Try this.

IntPtr val = new IntPtr((Int32)'A');
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_CHAR, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYDOWN, new IntPtr(VK_RETURN), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, new IntPtr(VK_RETURN), new IntPtr(0));
like image 77
bkribbs Avatar answered Oct 18 '25 09:10

bkribbs