I am trying to use sendkeys, but send it to a non focused program. For example, I want to use sendkeys to Notepad - Untitled, without it being focused. Sorry if it's unclear, I will elaborate. My current code is this:
string txt = Regex.Replace(richTextBox3.Text, "[+^%~()]", "{$0}");
System.Threading.Thread.Sleep(1000);
SendKeys.Send(txt + "{ENTER}");
If I use SendMessage, would anyone care to show me an example of what I should do? I don't find anything I found online very useful for my issue.
The following code I found from a previous SO answer. The PostMessage API will send a Windows message to a specific Windows handle. The code below will cause the key down event to fire for all instances of Internet Explorer, without giving focus, simulating that the F5 key was pressed. A list of additional key codes can be found here.
static class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const int VK_F5 = 0x74;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);
Thread.Sleep(5000);
}
}
}
It took me a while to figure it out for myself
Also here a usefull list of Virtual Key Codes
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern bool PostMessage(int hWnd, uint Msg, int wParam, int lParam);
private void button1_Click(object sender, EventArgs e)
{
const int WM_SYSKEYDOWN = 0x0104;
const int VK_RETURN = 0x0D;
IntPtr WindowToFind = FindWindow(null, "Notepad - Untitled"); // Window Titel
PostMessage(WindowToFind, WM_SYSKEYDOWN, VK_RETURN, 0);
}
Related
I found command System.Windows.Forms.SendKeys.Send() for sending keypress some key. This function work if open external app like a notepad and set focus and I will be see that my Key printed in this text field. How do same but with key down event, System.Windows.Forms.SendKeys.SendDown("A");, for example?
I tried call in Timer this command System.Windows.Forms.SendKeys.Send() but have runtime error associated with very fast taped.
You can't use the SendKeys class for that, unfortunately. You will need to go to a lower level API.
Poking a window with a keydown message
In Windows, keyboard events are sent to windows and controls via the Windows message pump. A piece of code using PostMessage should do the trick:
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
const uint WM_KEYDOWN = 0x0100;
void SendKeyDownToProcess(string processName, System.Windows.Forms.Keys key)
{
Process p = Process.GetProcessesByName(processName).FirstOrDefault();
if (p != null)
{
PostMessage(p.MainWindowHandle, WM_KEYDOWN, (int)key, 0);
}
}
Note that the application receiving these events may not do anything with it until a corresponding WM_KEYUP is received. You can get other message constants from here.
Poking a control other than the main window
The above code will send a keydown to the "MainWindowHandle." If you need to send it to something else (e.g. the active control) you will need to call PostMessage with a handle other than p.MainWindowHandle. The question is... how do you get that handle?
This is actually very involved... you will need to temporarily attach your thread to the window's message input and poke it to figure out what the handle is. This can only work if the current thread exists in a Windows Forms application and has an active message loop.
An explanation can be found here, as well as this example:
using System.Runtime.InteropServices;
public partial class FormMain : Form
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll")]
static extern IntPtr AttachThreadInput(IntPtr idAttach,
IntPtr idAttachTo, bool fAttach);
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
public FormMain()
{
InitializeComponent();
}
private void timerUpdate_Tick(object sender, EventArgs e)
{
labelHandle.Text = "hWnd: " +
FocusedControlInActiveWindow().ToString();
}
private IntPtr FocusedControlInActiveWindow()
{
IntPtr activeWindowHandle = GetForegroundWindow();
IntPtr activeWindowThread =
GetWindowThreadProcessId(activeWindowHandle, IntPtr.Zero);
IntPtr thisWindowThread = GetWindowThreadProcessId(this.Handle, IntPtr.Zero);
AttachThreadInput(activeWindowThread, thisWindowThread, true);
IntPtr focusedControlHandle = GetFocus();
AttachThreadInput(activeWindowThread, thisWindowThread, false);
return focusedControlHandle;
}
}
The good news-- if SendKeys worked for you, then you might not need to do all this-- SendKeys also sends messages to the main window handle.
I'm running a C# script on a large number of Excel workbooks that involves calling a macro in each workbook; the macro sometimes produces a MsgBox because of an error handler, and that pauses execution of the script until I click "OK" in the MsgBox.
The title text of the MsgBox is "Error in processSub", and the main text is "Error (Type Mismatch)".
I thought maybe I could have a concurrent thread that finds all currently open windows, and if it finds the MsgBox, clicks "OK". I'm trying to find the window using something like this:
using System.Diagnostics;
public Process getErrorWindow()
{
Process[] processList = Process.GetProcesses();
foreach (Process process in processList)
{
if (process.MainWindowTitle=="Error in processSub")
{
return process;
}
}
}
But this doesn't find anything. When I look through processList[], it only seems to find the main Excel window, and not any of the child windows that its VBA code produces. Is there a way to find the MsgBox and click its OK button?
You can use the winapi function FindWindow to retrieve the handle of a window by its title and class. Add the following code to your program:
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static IntPtr FindExcelErrorPopup()
{
return FindWindow(null, "Error in processSub");
}
To click the button:
IntPtr hwnd = FindExcelErrorPopup();
if (hwnd != IntPtr.Zero)
{
SetForegroundWindow(hwnd); // activates the window
SendKeys.SendWait("{ENTER}"); // send ENTER key
}
If the default button is not "OK", send some TAB strokes to select it before the ENTER.
Don't forget to put using System.Runtime.InteropServices; for the DllImport.
EDIT:
For remote desktop try this native method:
[DllImport("user32.dll")]
private static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
private const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
private const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;
And raise keys like this:
keybd_event(Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero); // key down
keybd_event(Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero); // key up
I'm running into a weird problem.
I have a WinForms application that opens another program (billing system emulator), sets it as a child window and then disables it. This works fine, the user cannot send any keys to the that child window, and the winforms application does its thing, sending commands to the child window.
However, it's been discovered that pushing the shift or control, even if the winforms application doesn't have focus, causes an error in the billing system emulator as they aren't valid keys. Users have taken to not using the shift or control keys while the winforms app runs but that's obviously not a practical solution.
My attempted solution was:
Global keyboard hook to capture when those keys are pressed.
Overriding OnKeyDown in the winforms application to stop those keys.
That however still doesn't solve the problem of the shift and alt keys being sent to the child window when the winforms app is not in focus. I can stop shift and alt globally while the winforms app is running but I don't think that is valid. So I need to somehow in the global hook stop the keypress for the winforms app and its children but allow globally. Any ideas/thoughts?
This is my code.
I don't think there's a good answer for your scenario... =\
Here's a hack you can try. It will "release" Control/Shift if they are down, then you send your message afterwards:
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int extraInfo);
[DllImport("user32.dll")]
static extern short MapVirtualKey(int wCode, int wMapType);
private void button1_Click(object sender, EventArgs e)
{
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
keybd_event((int)Keys.ShiftKey, (byte)MapVirtualKey((int)Keys.ShiftKey, 0), 2, 0); // Shift Up
}
if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
{
keybd_event((int)Keys.ControlKey, (byte)MapVirtualKey((int)Keys.ControlKey, 0), 2, 0); // Control Up
}
// ... now try sending your message ...
}
This obviously isn't foolproof.
I took a look at the only constructor of the globalKeyboardHook and looks like it is designed only for global hook. You can add another overload to hook into the current running module only like this:
class globalKeyboardHook {
[DllImport("kernel32")]
private static extern int GetCurrentThreadId();
[DllImport("user32")]
private static extern IntPtr SetWindowsHookEx(int hookType, KeyBoardProc proc, IntPtr moduleHandle, int threadId);
[DllImport("user32")]
private static extern int CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);
public globalKeyboardHook(bool currentModuleOnly){
if(currentModuleOnly){
proc = KeyBoardCallback;
//WH_KEYBOARD = 0x2
hhook = SetWindowsHookEx(2, proc, IntPtr.Zero, GetCurrentThreadId());
} else hook();
}
public delegate int KeyBoardProc(int nCode, IntPtr wParam, IntPtr lParam);
public int KeyBoardCallback(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0) {
Keys key = (Keys)wParam;
var lp = lParam.ToInt64();
//your own handling with the key
if ((lp >> 31) == 0)//Key down
{
//your own code ...
} else { //Key up
//your own code ...
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
KeyBoardProc proc;
//other code ...
}
//then use the new overload constructor instead of the parameterless constructor:
globalHook = new globalKeyboardHook(true);
NOTE: You can implement your own KeyDown and KeyUp event based on what I posted above (the comment your own code ...). After some searching I understand that the WH_KEYBOARD_LL supports global hook only while the WH_KEYBOARD is for thread hook only. That should be what you want instead of the WH_KEYBOARD_LL.
BTW, I doubt that the IMessageFilter which can be registered/added by your application can be used in this case. It also supports a PreFilterMessage method helping you to intercept any key and mouse messages at the application-level. You should try searching on that, it's easy to follow.
We have a legacy program with a GUI that we want to use under control of a C# program to compute some values. We can successfully enter values in the numerical input controls, press the compute button, and read the produced answers from text display boxes.
But we can't seem to control a pair of radio buttons .
Calling CheckRadioButton() returns a code of success, but the control does not change state.
Sending a message of BM_CLICK does not change the state.
Attempts at sending WM_LBUTTONDOWN and WM_LBUTTONUP events haven't changed the state.
Has anyone been successful at "remote control" of radio buttons?
Portions of code to illustrate what we are doing:
[DllImport("user32.dll", EntryPoint="SendMessage")]
public static extern int SendMessageStr(int hWnd, uint Msg, int wParam, string lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, long wParam, long lParam);
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError=true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", EntryPoint="CheckRadioButton")]
public static extern bool CheckRadioButton(IntPtr hwnd, int firstID, int lastID, int checkedID);
static IntPtr GetControlById(IntPtr parentHwnd, int controlId) {
IntPtr child = new IntPtr(0);
child = GetWindow(parentHwnd, GetWindow_Cmd.GW_CHILD);
while (GetWindowLong(child.ToInt32(), GWL_ID) != controlId) {
child = GetWindow(child, GetWindow_Cmd.GW_HWNDNEXT);
if (child == IntPtr.Zero) return IntPtr.Zero;
}
return child;
}
// find the handle of the parent window
IntPtr ParenthWnd = new IntPtr(0);
ParenthWnd = FindWindowByCaption(IntPtr.Zero, "Legacy Window Title");
// set "N" to 10
IntPtr hwndN = GetControlById(ParenthWnd, 17);
SendMessageStr(hwndN.ToInt32(), WM_SETTEXT, 0, "10");
// press "compute" button (seems to need to be pressed twice(?))
int hwndButton = GetControlById(ParenthWnd, 6).ToInt32();
SendMessage(hwndButton, BM_CLICK, 0, 0);
SendMessage(hwndButton, BM_CLICK, 0, 0);
// following code runs succesfully, but doesn't toggle the radio buttons
bool result = CheckRadioButton(ParenthWnd, 12, 13, 12);
Send the BM_SETCHECK message. Be sure to use a tool like Spy++ to see the messages.
in this case i used another message BM_SETSTATE
SendMessage((IntPtr)hWnd, Win32Api.BM_SETSTATE, (IntPtr)newState, IntPtr.Zero);
I wanna do a macro program for a game. But there is a problem with sending keys to only game application (game window). I am using keybd_event API for sending keys to game window. But I only want to send keys to the game window, not to explorer or any opened window while my macro program is running. When I changed windows its still sending keys. I tried to use Interaction.App with Visual Basic.dll reference. But Interaction.App only Focus the game window.
I couldn't find anything about my problem. Can anyone help me? Thanx
i fixed my problem.
in this field ;
PostMessage(hWnd, WM_KEYDOWN, key, {have to give lParam of the key});
otherwise it does not work.And we can control of ChildWindow Class with Spy++ tool of Microsoft.
Thanks everyone for helping.
Are you retrieving the handle of the window all the time, or are you remembering it?
If you use the FindWindow() API, you can simply store the Handle and use the SendMessage API to send key/mouse events manually.
FindWindow API:
http://www.pinvoke.net/default.aspx/user32.FindWindowEx
SendMessage API:
http://www.pinvoke.net/default.aspx/user32/SendMessage.html
VB
Private Const WM_KEYDOWN As Integer = &H100
Private Const WM_KEYUP As Integer = &H101
C#
private static int WM_KEYDOWN = 0x100
private static int WM_KEYUP = 0x101
class SendKeySample
{
private static Int32 WM_KEYDOWN = 0x100;
private static Int32 WM_KEYUP = 0x101;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, int lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
public static IntPtr FindWindow(string windowName)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.MainWindowHandle != IntPtr.Zero && p.MainWindowTitle.ToLower() == windowName.ToLower())
return p.MainWindowHandle;
}
return IntPtr.Zero;
}
public static IntPtr FindWindow(IntPtr parent, string childClassName)
{
return FindWindowEx(parent, IntPtr.Zero, childClassName, string.Empty);
}
public static void SendKey(IntPtr hWnd, System.Windows.Forms.Keys key)
{
PostMessage(hWnd, WM_KEYDOWN, key, 0);
}
}
Calling Code
var hWnd = SendKeySample.FindWindow("Untitled - Notepad");
var editBox = SendKeySample.FindWindow(hWnd, "edit");
SendKeySample.SendKey(editBox, Keys.A);
If you want to communicate with a game, you typically will have to deal with DirectInput, not the normal keyboard API's.