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));
}
}
}
如果我设置val = char 'm'
(它是分解:109,己烷:0x6D),然后当窗口得到它示出了炭消息“ - ”由于某种原因(这是十进制45,十六进制0x2D)。 我初步怀疑六角/ DEC格式化的问题,但我错了。 作为一个新手WINAPI,我的问题似乎与PostMessage的()语法。 我怎么能发送正确的消息有窗口中显示正确的字符?