Why does PostMessage not work with all VK values? - c#

I'm attempting to simulate keyboard input to an window programmatically. I realize SendInput is the optimal method here, but I need to be able to send this keystroke to a window that is not currently in focus.
As such, I'm trying to use PostMessage instead.
The following works for simulating the input of the F5 key in notepad, but not for the spacebar.
using System.Diagnostics;
using System.Runtime.InteropServices;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool PostMessage(IntPtr hWnd, UInt32 msg, uint wParam, int lParam);
const uint WM_KEYDOWN = 0x0100;
const uint WM_KEYUP = 0x0101;
const int VK_SPACE = 0x20;
const int VK_F5 = 0x74;
while(true)
{
Process[] processes = Process.GetProcessesByName("notepad");
foreach (Process process in processes)
{
PostMessage(process.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);
PostMessage(process.MainWindowHandle, WM_KEYUP, VK_F5, 0);
Thread.Sleep(5000);
PostMessage(process.MainWindowHandle, WM_KEYDOWN, VK_SPACE, 0);
PostMessage(process.MainWindowHandle, WM_KEYUP, VK_SPACE, 0);
}
}
Any idea why? Is there a better why I should go about this?

Related

Infinity pressed keys 'PostMessage' to hidden window

Hello I'm trying to send keys to hidden game and I have 1 problem, when I send the keys to game it press only the first one and it's not ending e.g like it's pressed W for infinity time and cant send the next key. I think the key it's not going up.
My code:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Naura_2._0
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
public Form1()
{
InitializeComponent();
}
private const UInt32 WM_KEYDOWN = 0x0100;
private const UInt32 WM_KEYUP = 0x0101;
private const int VK_KEY_W = 0x57;
private void button1_Click(object sender, EventArgs e)
{
IntPtr hWnd = FindWindow(null, "Game Title");
if (!hWnd.Equals(IntPtr.Zero))
{
PostMessage(hWnd, WM_KEYDOWN, VK_KEY_W, 0);
PostMessage(hWnd, WM_KEYUP, VK_KEY_W, 5);
}
}
}
}
Options for sending key presses
If the Window must be in focus to send keys presses use SendInput instead of PostMessage as it is designed for this very process. This scenario is quite common with games where they automatically pause if the game window is not focus so sending any keys will likely do nothing.
If you would like the window focus to be optional while sending key presses then PostMessage seems like the only way.
Solution for sending key presses using PostMessage
To "Emulate" a keypress a Virtual Key Codes (the key 'A') and Scan Codes (the location on the keyboard of 'A') and some additional flags, Keystroke Message Flags, are sent.
PostMessage(hWndChild, WM_KEYDOWN, virtualKey, scanCode << 16 | 0x0000001);
PostMessage(hWndChild, WM_KEYUP, virtualKey, scanCode << 16 | 0xC0000001);
You can map between virtualKeys and scanCodes using MapVirtualKey
Full program example
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
const uint WM_KEYDOWN = 0x0100;
const uint WM_KEYUP = 0x0101;
const uint MAPVK_VK_TO_VSC = 0x00;
// virtual key codes
const uint VK_ESCAPE = 0x1B;
const uint VK_LSHIFT = 0xA0;
const uint VK_LCONTROL = 0xA2;
const uint VK_OEM_2 = 0xBF; // For the US standard keyboard, the '/?' key
const uint VK_W = 'W';
const uint VK_A = 'A';
const uint VK_S = 'S';
const uint VK_D = 'D';
// Scan Code for US keyboard layout
const uint VSC_W = 0x11; // MapVirtualKey('W', MAPVK_VK_TO_VSC);
const uint VSC_A = 0x1E; // On QUERY MapVirtualKey('A', MAPVK_VK_TO_VSC);
// On AZERY MapVirtualKey('Q', MAPVK_VK_TO_VSC);
const uint VSC_S = 0x1F;
const uint VSC_D = 0x20;
const uint VSC_LSHIFT = 0x2A;
// Write 'w' (yes lower case) in Notepad.exe (*Untitled - Notepad)
static void Example1()
{
uint keyPress = VK_W;
uint scanCode = MapVirtualKey(keyPress, MAPVK_VK_TO_VSC);
IntPtr hWnd = FindWindow(null, "*Untitled - Notepad");
IntPtr hWndChild = FindWindowEx(hWnd, IntPtr.Zero, "Edit", string.Empty);
PostMessage(hWndChild, WM_KEYDOWN, keyPress, scanCode << 16 | 0x0000001);
Thread.Sleep(42);
PostMessage(hWndChild, WM_KEYUP, keyPress, scanCode << 16 | 0xC0000001);
}
// Write 'help' (yes lower case) in Notepad.exe (*Untitled - Notepad)
static void Example2()
{
string text = "help";
IntPtr hWnd = FindWindow(null, "*Untitled - Notepad");
IntPtr hWndChild = FindWindowEx(hWnd, IntPtr.Zero, "Edit", string.Empty);
foreach (var c in text)
{
uint keyPress = char.ToUpper(c);
uint scanCode = MapVirtualKey(keyPress, MAPVK_VK_TO_VSC);
PostMessage(hWndChild, WM_KEYDOWN, keyPress, scanCode << 16 | 0x0000001);
Thread.Sleep(42);
PostMessage(hWndChild, WM_KEYUP, keyPress, scanCode << 16 | 0xC0000001);
Thread.Sleep(142);
}
}
}
Some additional background reading
https://handmade.network/forums/t/2011-keyboard_inputs_-_scancodes,_raw_input,_text_input,_key_names
Arriving at the solution
Visual Studio comes with a program called Spy++ which can be used to view the message queue of any window.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\spyxx.exe
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\spyxx_amd64.exe
where spyxx.exe is used to inspect 32bit processes and spyxx_amd64.exe is used to inspect 64bit process. Using Spy++ and the documentation, Keystroke Message Flags, I was able to view the WM_KEYDOWN and WM_KEYUP and imitate the desired behavior using PostMessage.
Potential short falls
You can send a shift key and most games should receive the shift key but operations like [Shift]+[A] in a textbox will result in 'a'. Windows uses some other mechanism to generate the capital letters.
Some programs may used GetKeyboardState it which case posting messages won't do anything since it queries the keyboard and ignores the messages. Note the there is a SetKeyboardState which can be used to set which keys are pressed and hence communicate with these programs.

Sending keystroke/mouseclick via PostMessage() in C#

I already got mouseclick to work with one issue. If I set delay between WM_MBUTTONDOWN and WM_MBUTTONUP to more than 5 ms it won't work. Why is that?
[DllImport("user32.dll")]
public static extern IntPtr
PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public void MouseClick(short x, short y)
{
IntPtr lParam = (IntPtr)((x & 0xFFFF) | ((y & 0xFFFF) << 16));
const uint WM_MBUTTONDOWN = 0x0201;
const uint WM_MBUTTONUP = 0x0202;
PostMessage(hwnd, WM_MBUTTONDOWN, IntPtr.Zero, lParam);
//System.Threading.Thread.Sleep(100);
PostMessage(hwnd, WM_MBUTTONUP, IntPtr.Zero, lParam);
}
Now, my goal is to send keystroke to minimized window (directx game). I tried using similar approach but nothing works. I bet that wParam is the problem.
const uint WM_KEYDOWN = 0x100;
const uint WM_KEYUP = 0x101;
const uint WM_CHAR = 0x102;
const int VK_W = 0x57;
const int VK_S = 0x53;
PostMessage(hwnd, WM_KEYDOWN, (IntPtr)VK_W, IntPtr.Zero);
PostMessage(hwnd, WM_KEYUP, (IntPtr)VK_W, IntPtr.Zero);
How do I get this to work?
Remember that the window will be minimized so I can't use SendKeys or SendInput.
UPDATE:
This code works, but only for typing in in-game chat.
const int VK_G = 0x47;
const uint WM_KEYDOWN = 0x100;
PostMessage(hwnd, WM_KEYDOWN, VK_G, 0);
I can't use it to walk forward etc.

C# Simulating keyboard press on OS below Windows 8

I am using the following code in C# to simulate the keyboard pressing:
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);
void sim_key(string text, string proc)
{
var process = Process.GetProcessesByName(proc).FirstOrDefault();
if (process != null && process.MainWindowHandle != IntPtr.Zero)
{
SetForegroundWindow(process.MainWindowHandle);
SendKeys.Send(kat_id);
}
}
I tested it on Windows Xp, 7, 8.1, 10, and Server 2012. On windows 7 and Xp, the external app window is handled properly, however the keys are not being sent. On systems above Win 7 everything is correct. How should I fix it?
Edit:
I checked it on .NET 4.0 Client Profile and .NET 4.6.1 on 32 and 64 bit machines, but results are the same as described above.
I think you can go with this rough code
const int WM_CHAR = 0x0102;
const int WM_KEYDOWN = 0x0100;
if (process != null && process.MainWindowHandle != IntPtr.Zero)
{
PostMessage(process.MainWindowHandle, WM_CHAR, (int) <a character you want to send> , 1);
}
Use
PostMessage(process.MainWindowHandle, WM_KEYDOWN, 13, 1);
to send the "Enter".
Note that you can use SendMessage instead of PostMessage. The difference is the last one does not wait the processing of the key. They have the same signature:
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
You don't need calling SetForegroundWindow(process.MainWindowHandle); if you just want to send keys.
Thank you for your answer. I tried using PostMessage to send Ctrl+F10 to the other window. Here is my code:
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int VK_CONTROL = 0x11;
public const int VK_F10 = 0x79;
PostMessage(process.MainWindowHandle, WM_KEYDOWN, VK_CONTROL, null);
PostMessage(process.MainWindowHandle, WM_KEYDOWN, VK_F10, null);
PostMessage(process.MainWindowHandle, WM_KEYUP, VK_F10, null);
PostMessage(process.MainWindowHandle, WM_KEYUP, VK_CONTROL, null);
However, it doesn't pass the keys to the app.

Simulate "Key Press" on NON Foreground Window

I am currently developing a program that will send a "key press" (the letter A or 0x41 in virtual key codes) to another program (notepad) every X seconds.
The problem is that for it to work I need the other program (notepad) to be in the FOREGROUND, example :
Process[] processes = Process.GetProcessesByName("notepad");
foreach (Process proc in processes) {
SetForegroundWindow(proc.MainWindowHandle);
// Do Whatever
}
Thread.Sleep(1000);
Is there a way to do that WITHOUT notepad having to be in the foreground ?
Like something that could run in the background ?
You could do it via winApi. Try to use SendMessage
According to this link you can do following:
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public static void sendKeystroke(ushort k)
{
const uint WM_KEYDOWN = 0x100;
const uint WM_SYSCOMMAND = 0x018;
const uint SC_CLOSE = 0x053;
IntPtr WindowToFind = FindWindow(null, "Untitled1 - Notepad++");
IntPtr result3 = SendMessage(WindowToFind, WM_KEYDOWN, ((IntPtr)k), (IntPtr)0);
//IntPtr result3 = SendMessage(WindowToFind, WM_KEYUP, ((IntPtr)c), (IntPtr)0);
}

Click on 'OK' button of message box using WINAPI in c#

I am trying to click on 'OK' button on a message box of C# windows form using winapi. Below is the code that I am working on.
private const int WM_CLOSE = 16;
private const int BN_CLICKED = 245;
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
//this works
hwnd = FindWindow(null, "Message");
if(hwnd!=0)
SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);
//this doesn't work.
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "ok");
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
Though i get a value in hwndChild, it is not recognising BN_CLICKED.
I am not sure what am I missing. any help?
I am trying to close the message box button of another application and this is what I am doing. But, I m still missing something.
IntPtr hwndChild = IntPtr.Zero;
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero,' '"Button", "OK");
SendMessage((int)hwndChild, WM_COMMAND, (BN_CLICKED '<<16) | IDOK, hwndChild);
BN_CLICKED is not a message. You need to send a WM_COMMAND message containing the BN_CLICKED notification and the button ID in the wParam and the button handle in lParam.
The parent window of the button receives this notification code
through the WM_COMMAND message.
private const uint WM_COMMAND = 0x0111;
private const int BN_CLICKED = 245;
private const int IDOK = 1;
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
SendMessage(hwndChild, WM_COMMAND, (BN_CLICKED << 16) | IDOK, hwndChild);
Finallu, this works for me.
First click probably activates the window and second click clicks the button.
SendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);
SendMessage(btnHandle, WM_LBUTTONUP, 0, 0);
SendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);
SendMessage(btnHandle, WM_LBUTTONUP, 0, 0);

Categories

Resources