ホットキーとイベントハンドラ

春Mに限らず、ファイラやランチャはホットキーで立ち上がってくれないと困る。ホットキー+キーボード操作でユーティリティーが起動できれば、ほぼ全部の操作がキーボードだけで済む。

というわけで、ホットキーのサンプル。

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices ;

namespace WinApp {
  public class TestForm : Form {

    const int MOD_ALT     = 0x0001 ;
    const int MOD_CONTROL = 0x0002 ;
    const int MOD_SHIFT   = 0x0004 ;
    const int WM_HOTKEY   = 0x0312 ;
    const int HOTKEY_ID   = 0x0001 ;

    [DllImport("user32.dll")] 
    extern static int RegisterHotKey(IntPtr HWnd, int ID, int MOD_KEY, int KEY) ;

    [DllImport("user32.dll")] 
    extern static int UnregisterHotKey(IntPtr HWnd, int ID) ;

    private void TestForm_Load(object sender, System.EventArgs e) {
      int r = RegisterHotKey(this.Handle, HOTKEY_ID, MOD_CONTROL | MOD_ALT, (int)Keys.W);
      Console.WriteLine(r);
    }

    private void TestForm_Closed(object sender, System.EventArgs e) {
      int r = UnregisterHotKey(this.Handle, HOTKEY_ID) ;
      Console.WriteLine(r);
    }
    
    public TestForm() {
      ClientSize = new Size(200, 200);
      Text = "TestForm";
      this.Load += new EventHandler(TestForm_Load);
      this.Closed += new EventHandler(TestForm_Closed);
    }

    protected override void WndProc(ref Message m) {
      base.WndProc(ref m);
      if (m.Msg == WM_HOTKEY && (int)m.WParam == HOTKEY_ID) {
        Console.WriteLine("Hello");
      }
    }

    [STAThread]
    static void Main() {
      Application.Run(new TestForm());
    }
  }
}

実行結果

 $ csc hotkey.cs
 $ ./hotkey.exe
 1      ← ホットキー登録成功 (0以外の返り値で成功)
 Hello  ← ここで Ctrl+Alt+Wを押した
 1      ← ホットキー削除成功

イベントハンドラとか、どうせこうなってるだろうとやってみたらうまくいった。Javaを知っている人にはC#は驚き最小の言語に見える。