public partial class Form1 : Form
{
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public const Int32 WM_CHAR = 0x0102;
public const Int32 WM_KEYDOWN = 0x0100;
public const Int32 WM_KEYUP = 0x0101;
public const Int32 VK_RETURN = 0x0D;
public Form1()
{
InitializeComponent();
}
public bool working;
private void button1_Click(object sender, EventArgs e)
{
Process[] proc = Process.GetProcessesByName("processname");
if (proc[0] == null || proc.Length == 0)
{
Debug.WriteLine("Process not found.");
return;
}
foreach (char c in textBox1.Text)
{
// char ascii value in decimal
int charValue = c;
// char ascii value in hex
string hexValue = charValue.ToString("X");
IntPtr val = new IntPtr(c);
Debug.WriteLine(c + " = dec: " + charValue + ", hex: " + hexValue + ", val: " + val);
PostMessage(proc[0].MainWindowHandle, WM_KEYDOWN, val, new IntPtr(0));
PostMessage(proc[0].MainWindowHandle, WM_CHAR, val, new IntPtr(0));
PostMessage(proc[0].MainWindowHandle, WM_KEYUP, val, new IntPtr(0));
PostMessage(proc[0].MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_RETURN), new IntPtr(0));
PostMessage(proc[0].MainWindowHandle, WM_KEYUP, new IntPtr(VK_RETURN), new IntPtr(0));
}
}
}
If I set val = char 'm'
(which is dec: 109, hex: 0x6D) then when the window gets the message it shows the char '-' for some reason (which is dec 45, hex 0x2D). I initially suspected hex/dec formating issues but I was mistaken.
As a winapi newbie, my problem seems to be with PostMessage() syntax. How can I send the correct message to have the window display the correct character?
The source of all my confusion stemmed from the
PostMessage
syntax forWM_CHAR
. I assumed thewParam
was a standard ascii hex keycode and it was not. It was actually a (hex) virtual keycode.This explains why 0x6D was sending minus instead of 'm'!
0x6C and 108 are the same thing in C#, both are integers, so...
and
are functionally equivilant.
Therefore in your code above, you should be able to use: