C#如何让失去焦点的窗口还能捕捉到键盘事件?

标签: WinForm C#
发布时间: 2010/2/16 18:08:10

RT
实际上我在做一个倒计时软件,用来计时游戏里人物的增益BUFF状态。
我想要的效果是我游戏时倒计时软件(快捷键F1)还能最前,但没有焦点。因为我要操作游戏人物。
当我按F1时,倒计时软件还能响应他自己的功能。
我是个编程小白,最近才学C#,所以最好有示例代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace sdg
{
    public partial class Form1 : Form. {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "按F1";
        }
        private void button1_Click(object sender, EventArgs e)
        {
            label2.Text = "快捷键生效!";
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)//是针对窗口的快捷键不是Button1的
        {
            if (e.KeyCode == Keys.F1)
            {
                button1_Click(sender, e);
            }
        } 
    }
} 

解决方法 1:

刚好前段时间做了个程序,就是关于全局快捷键的。楼主加上这些东西,formload的时候register下,formclose的时候 unregister下,就ok了。

        using System.Runtime.InteropServices;

        /// <summary>
        /// Register HotKeys
        /// </summary>
        /// <param name="hWnd">handle to window</param>
        /// <param name="id">hot key identifier</param>
        /// <param name="fsModifiers">key-modifier options</param>
        /// <param name="vk">virtual-key code</param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);

        /// <summary>
        /// UnRegister HotKeys
        /// </summary>
        /// <param name="hWnd">handle to window</param>
        /// <param name="id">hot key identifier</param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnRegisterHotKey(IntPtr hWnd,int id);

        /// <summary>
        /// Keys for Combination
        /// </summary>
        [Flags()]
        public enum KeyModifiers{
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

        /// <summary>
        /// Override the WndProc,When Lose focus it can also activate the registered hot keys
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312; //Press the HotKey
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    callScr();
                    break;
            }
            base.WndProc(ref m);
        }

官方微信
官方QQ群
31647020