Search code examples
c#automationunmanagedsendmessagepostmessage

Why does PostMessage send multiple keys when sending lower case keys?


I'm using PostMessage to send keys to a minimsed firefox instance. This code below works fine for Uppercase characters but when I send Lowercase it seems to send 3 of each character sent.

This is a cut down example of sending the "c" character. I know its not firefox because it does the same in notepad.

This is the spy++ output for when I manually send input to the window

<000001> 000204B6 P WM_KEYDOWN nVirtKey:'C' cRepeat:1 ScanCode:2E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000002> 000204B6 P WM_CHAR chCharCode:'99' (99) cRepeat:1 ScanCode:2E fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000003> 000204B6 P WM_KEYUP nVirtKey:'C' cRepeat:1 ScanCode:2E fExtended:0 fAltDown:0 fRepeat:1 fUp:1

This is the spy++ output for when my code sends it

<000001> 000906D4 P WM_KEYDOWN nVirtKey:'C' cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000002> 000906D4 P WM_CHAR chCharCode:'99' (99) cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000003> 000906D4 P WM_KEYUP nVirtKey:'C' cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000004> 000906D4 P WM_CHAR chCharCode:'99' (99) cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
<000005> 000906D4 P WM_CHAR chCharCode:'99' (99) cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0

What am i doing wrong here?

[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;

IntPtr val = new IntPtr((Int32)'c');
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));

Solution

  • Figured this out. All I needed was the below!

    char Letter = 'a';
    PostMessage(WindowHandle, WM_CHAR, (IntPtr)Letter, new IntPtr(0));