如何编写全局热键 [英] How do I write a Global hotkey

查看:76
本文介绍了如何编写全局热键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我开始制作一个简短的应用程序来跟踪我在游戏中运行的圈数。我想要完成的是每次我在游戏中完成一圈同时仍然将焦点设置到游戏时使用全局热键来说按Ctrl + A将一圈添加到计数器而不必将焦点更改为计数器。



到目前为止这是我所拥有的

Hi,

I started working on a short application to keep track of laps I run around a course in a game I play. What I am trying to accomplish is that every time I complete a lap in the game while still having the focus set to the game use a global hotkey to say press Ctrl + A to add a lap to the counter without having to change focus to the lap counter.

So far this is what I have

<pre lang="c#">public partial class Form1 : Form
    {
        KeyboardHook hook = new KeyboardHook();
        int count = 0;
        public Form1()
        {
            InitializeComponent();
          
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            count++;
            CounterLabel.Text = count.ToString();
            


        }





我想知道是否有人能够给关于全局关键钩的任何提示。



我花了很多时间浏览msdn和其他一些网站,但仍然无法弄明白到底是什么做。



谢谢,



JosephCj



I was wondering if anyone would be able to give me any tips on the global keyhook.

I've spent quite a bit of time looking through msdn and some other sites but still can't figure out exactly what to do.

Thank you,

JosephCj

推荐答案

Global Keyhook通常指操作系统范围内的键挂钩:适用于Windows中的任何位置,并在满足特定条件(用户操作)时触发(运行应用程序)中的事件。



在我看来,你想要的不是一个全局钩子,而只是一种在你的应用程序中拦截Control-A的方法。



除非你在Win Forms应用程序中使用一些游戏引擎,它在自己的窗口中接管键处理并阻止你获取关键事件,这很容易。



这是一种技术当按下Alt-A时,所有Win Form应用程序按键并执行某些操作:
"Global Keyhook" usually refers to a key-hook which is OS-wide: works anywhere in Windows, and triggers an Event in your (running Application) when certain conditions (user actions) are met.

It seems to me what you want here is not a global hook but just a way to intercept Control-A in your Application.

Unless you are using some game-engine inside your Win Forms app that "takes over" key-handling in its own window and blocks you from getting keyevents, this is easy.

Here's one technique that will intercept all Win Form app keystrokes and "do something" when Alt-A is pressed:
private int count = 0;

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // look for Control A
    if (keyData == (Keys.Control| Keys.A))
    {
        count++;
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

请记住,许多操作系统定义的键盘快捷键被许多Windows用户视为理所当然:如果你覆盖像Control-A这样的标准Win快捷键,你可能会让人感到困惑使用您的应用程序。

Do keep in mind that many OS defined keyboard shortcuts are taken-for-granted by many Windows users: if you over-ride a standard Win shortcut like Control-A you may confuse people using your Application.


这篇关于如何编写全局热键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆