繁体   English   中英

如果程序最小化或在系统托盘中,如何检测ctrl键两次

[英]How to detect the ctrl key is pressed twice if the program is minimized or in system tray

如果程序最小化或在系统托盘中,如何检测ctrl键两次

我正在尝试开发ac#程序,当按下控制键两次时,主窗体将显示给用户。 我找到了热键组合的样本,但这不是组合的热键,比如控制+其他一些键。 这就像谷歌桌面应用程序,当按下控制键两次时显示搜索框。

这似乎是键盘挂钩WH_KEYBOARD )的情况。

你可以做的是每次按下按键时捕获,也许在后台工作人员中比较时间差。

设置一个阈值,如果它低于那个,你会认为它是双击并做你需要的。

未经测试的组件可能看起来像:

    private readonly DateTime _originDateTime = new DateTime(0);
    private DateTime _lastKeyPress;

连接工人:

        _backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = false };
        _backgroundWorker.DoWork += DoBackgroundWork;
        _backgroundWorker.RunWorkerAsync();

实现DoBackgroundWork方法:

    private void DoBackgroundWork(object sender, DoWorkEventArgs doWorkEventArgs)
    {
        do
        { 
                if (_lastKeyPress != _originDateTime)
                {
                    Thread.Sleep(DelayInMilliseconds);
                    DateTime now = DateTime.Now;

                    TimeSpan delta = now - _lastKeyPress;

                    if (delta < new TimeSpan(0, 0, 0, 0, DelayInMilliseconds))
                    {
                        continue;
                    }
                }

                //do stuff

        } while (true);
    }

别忘了抓住钥匙:

    private void SomeEvent_KeyDown(object sender, KeyEventArgs e)
    {
        _lastKeyPress = DateTime.Now;
    }

这基于XPath Visualizer

使用像foxx1337建议的键盘钩子,然后执行以下操作:

int triggerThreshold = 500; //This would be equivalent to .5 seconds
int lastCtrlTick = 0;

private void OnCtrlPress()
{
    int thisCtrlTick = Environment.TickCount;
    int elapsed = thisCtrlTick - lastCtrlTick;
    if (elapsed <= triggerThreshold)
    {
        LaunchYourAppOrWhatever();
    }
    lastCtrlTick = thisCtrlTick;
}

如建议的键盘挂钩。 CodePlex为您提供了很好的包装,无论您的应用处于什么状态,您都可以在其中获得.NET API,只需提升Key和Mouse事件。

更新:已接受的答案中提到的托管包装器.NET库已移至此处 现在还有一个nuget包MouseKeyHook可用。

最近增加了对检测快捷方式,密钥组合和序列的支持。 这是一个用法示例:

void DoSomething()
{
    Console.WriteLine("You pressed UNDO");
}

Hook.GlobalEvents().OnCombination(new Dictionary<Combination, Action>
{
    {Combination.FromString("Control+Z"), DoSomething},
    {Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); }}
});

有关更多信息,请参阅: 检测组合键和Seuqnces

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM