上帝!前几天我刚刚找到了完美的课程。我花了一段时间才找到原始来源:
http://www.codeproject.com/KB/cs/globalhook.aspx
我完全根据您的需要单独使用了这个(和 SendKeys),您需要使用 Handle=true 来阻止原始密钥消息。
SendKeys 有点难看...如果您愿意,可以寻找替代品.. 但是 SendKeys 会为您工作。
使用 SendKeys 类似于:
private void HookManager_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D){
e.Handled = true;
SendKeys.Send("F");
}
}
实际上,我也使用这种方法来确定哪个 prccess 的窗口处于焦点位置,因此如果您在另一个应用程序上,该应用程序将什么也不做:
/// <summary>
/// The GetForegroundWindow function returns a handle to the foreground window.
/// </summary>
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
static bool IsProcessFocused(string processname)
{
if (processname == null || processname.Length == 0)
{
throw new ArgumentNullException("processname");
}
Process[] runninProcesses = Process.GetProcessesByName(processname);
IntPtr activeWindowHandle = GetForegroundWindow();
foreach (Process process in runninProcesses)
{
if (process.MainWindowHandle.Equals(activeWindowHandle))
{
return true;
}
}
// Process was not found or didn't had the focus.
return false;
}