最近在寫一些遊戲的模擬人性化操作小程式...絕對不是外掛= =
碰到了一些問題,就是想要在按特殊按鍵的時候自動執行或關閉程式
在網路上查了一下資料,發現可以用註冊快速鍵的方式來完成
程式碼大概長下面這個樣子
using的部分添加這個鬼
using System.Runtime.InteropServices;
宣告的部分添加四個鬼
[DllImport("user32.dll")] 
public static extern bool RegisterHotKey(IntPtr hWnd, 
        int id, // handle to window 
        uint fsModifiers, // key-modifier options 
        Keys vk // virtual-key code 
);
[DllImport("user32.dll")] 
public static extern bool UnregisterHotKey(IntPtr hWnd,
        int id // hot key identifier 
);
protected override void WndProc(ref Message m)
{
            const int WM_HOTKEY = 0x0312; 
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    ProcessHotkey(m); //按下热键时调用ProcessHotkey()函数
                    break;
            }
            base.WndProc(ref m); //将系统消息传递自父类的WndProc 
}
private void ProcessHotkey(Message m)
{
            IntPtr id = m.WParam;
            
            string sid = id.ToString();
            switch (sid)
            {
                case "100": MessageBox.Show("left"); break; 
                case "200": MessageBox.Show("right"); break; 
                case "300":
                    this.Visible = true;
                    break;
                case "400":
                    this.Visible = false;
                    break;
            }
}
初始化的部分添加隨便鬼
public Form1()
{
        InitializeComponent();
        RegisterHotKey(Handle, 100, 2, Keys.Left); // Control + 鍵盤左
        RegisterHotKey(Handle, 200, 2, Keys.Right); //Control + 鍵盤右
        RegisterHotKey(Handle, 300, 2, Keys.Up); // Control + 鍵盤上
        RegisterHotKey(Handle, 400, 2, Keys.Down); // Control + 鍵盤下
         ...
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
        UnregisterHotKey(Handle, 100); 
        UnregisterHotKey(Handle, 200); 
        UnregisterHotKey(Handle, 300);
        UnregisterHotKey(Handle, 400); 
}
沒有留言:
張貼留言
您可以使用一些 HTML 標記,例如 <b>, <i>, <a>