我尝试使用WinAPI模拟一些关键事件。我想按一下WIN键,但我的代码无效。在示例中,我为每个过程使用VK_F1。
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ConsoleApplication69
{
class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const UInt32 WM_KEYUP = 0x0101;
const int VK_F1 = 112;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static void Main(string[] args)
{
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
SendMessage(proc.MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_F1), IntPtr.Zero);
SendMessage(proc.MainWindowHandle, WM_KEYUP, new IntPtr(VK_F1), IntPtr.Zero);
}
}
}
}
答案 0 :(得分:1)
要模拟键盘输入,请使用SendInput
。这正是这个API的作用。 “将F1发送到每个窗口”并不是一个好主意,因为您将向没有键盘焦点的窗口发送击键。谁知道他们会如何回应。
键盘输入的细微差别比你要考虑的要多得多; See this question for considerations about emulating keyboard input
答案 1 :(得分:0)
所以我使用了此网址中的代码:SendKeys.Send and Windows Key
它工作正常!
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ConsoleApplication69
{
class Program
{
static void Main(string[] args)
{
KeyboardSend.KeyDown(Keys.LWin);
KeyboardSend.KeyUp(Keys.LWin);
}
}
static class KeyboardSend
{
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
private const int KEYEVENTF_EXTENDEDKEY = 1;
private const int KEYEVENTF_KEYUP = 2;
public static void KeyDown(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
}
public static void KeyUp(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
}
tnx帮助大家!