I'm wondering how to use SendMessage() or PostMessage() to send keystrokes to an inactive window. Could someone provide me with a simple code that sends a few characters and the enter button to notepad, while it's in the background?
Printable View
I'm wondering how to use SendMessage() or PostMessage() to send keystrokes to an inactive window. Could someone provide me with a simple code that sends a few characters and the enter button to notepad, while it's in the background?
This code is VB but it should be fairly obvious what it's doing:Here are the API declarations, which are in C#:vb.net Code:
Dim loginDialogueHandle As IntPtr = IntPtr.Zero 'Get the handle of the POS login dialogue. Do Threading.Thread.Sleep(50) loginDialogueHandle = NativeMethods.FindWindow(My.Resources.RmsPosFormClassNameString, "Login") Loop Until loginDialogueHandle <> IntPtr.Zero 'TODO: Hide login window in release. 'NativeMethods.ShowWindow(loginDialogueHandle, NativeConstants.SW_HIDE) 'Get the handles of the user ID and password fields and the OK button. Dim userIDFieldHandle As IntPtr = NativeMethods.FindWindowEx(loginDialogueHandle, _ IntPtr.Zero, _ My.Resources.RmsPosTextBoxClassNameString, _ String.Empty) Dim passwordFieldHandle As IntPtr = NativeMethods.FindWindowEx(loginDialogueHandle, _ userIDFieldHandle, _ My.Resources.RmsPosTextBoxClassNameString, _ String.Empty) Dim frameHandle As IntPtr = NativeMethods.FindWindowEx(loginDialogueHandle, _ IntPtr.Zero, _ My.Resources.RmsPosFrameClassNameString, _ String.Empty) Dim okButtonHandle As IntPtr = NativeMethods.FindWindowEx(frameHandle, _ IntPtr.Zero, _ My.Resources.RmsPosButtonClassNameString, _ "OK") If userIDFieldHandle <> IntPtr.Zero Then 'Enter the user ID. NativeMethods.SendMessage(userIDFieldHandle, _ NativeConstants.WM_SETTEXT, _ 0, _ "1") End If If passwordFieldHandle <> IntPtr.Zero Then 'Enter the password. NativeMethods.SendMessage(passwordFieldHandle, _ NativeConstants.WM_SETTEXT, _ 0, _ "password") End If If okButtonHandle <> IntPtr.Zero Then 'Click the OK button. NativeMethods.SendMessage(okButtonHandle, _ NativeConstants.BM_CLICK, _ 0, _ 0) End IfYou should download and install the API Viewer, which can help you with unmanaged function and constant declarations.Code:[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpszClass,
string lpszWindow);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd,
int wMsg,
int wParam,
int lParam);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd,
int wMsg,
int wParam,
string lParam);