I need to simulate a keystroke in a third-party application. Say I have a C # application that needs to send "8" to the Calculator application. I can not use SendKeys.Net or keybd_event win32 api because they both require the window to be the most active, which is not the case in my situation.
So this leaves me with calls to sendMessage and postMessage. I tried for the past three hours to try to get some results, but now I am 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 am making four attempts to contact the Calculator. Using sendMessage and PostMessage to close the window, as well as to send the key 7. Nothing works. The FindWindow method works because I get the application handler (I even tried to start the process itself and access it using process.MainWindowHandler, but no luck). There are no errors or exceptions, but nothing is done in the calculator.
I also tried the same with a notebook, and nothing has changed.
c # handler keypress sendmessage postmessage
Joao oliveira
source share