KeyEventArgs到Timer.Tick

时间:2017-08-23 13:25:40

标签: c#

我尝试将KeyEventArgs设置为Tick。如果有人认为我为什么要使用计时器,那么它也需要在窗口外检测按键。

我没有"错误"在这段代码中,但是当我运行程序时:

Exception Unhandled. System.NullReferenceExpetion: (i try to translate) 'Your object referral can't define object occurrence'

现在我正在使用的是



private void Form1_Load(object sender, EventArgs e)
        {
            A.Start();
            A.Interval = 1;
        }

private void A_Tick(object sender, EventArgs e)
        {
            KeyEventArgs ke = e as KeyEventArgs;
            if (ke.KeyCode == Keys.R) 
            {
            test = true;     
            }       
        }
            




我真的需要帮助,因为这个错误已经很久了。感谢

1 个答案:

答案 0 :(得分:1)

通过查看您将问题放在一起的方式,我们似乎正在尝试使用计时器检测按键。相反,您可以使用Form的KeyPress事件。

使用:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.SOMETHING)
    {
        //do something
    }
}

不要忘记为表单设置KeyPreview = true;

编辑:如果您需要检测按键甚至没有焦点(在表单之外),您需要通过挂钩来获取全局热键。您需要以下内容:

首先包括这个:

using System.Runtime.InteropServices;

你需要在课堂上占据优势:

[DllImport("user32.dll")] 
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
const int HOTKEY = 1;

你需要在Form的Load中调用它:

RegisterHotKey(this.Handle, HOTKEY, (uint)ModifierKeys.SOMETHING, (uint) Keys.SOMETHING);

然后你需要处理印刷机:

protected override void WndProc(ref Message m) 
{
    if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY) 
    {
        //do something when pressed
    }
    base.WndProc(ref m);
}
相关问题