LoginSignup
6
8

More than 5 years have passed since last update.

特定のキーが押されているか確認する

Posted at

押されている修飾キーを調べる

EXE起動時にShiftキーが押されているか

    [System.STAThread()]
    private static void Main() {
        if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) {
            Application.Run(new Form1());
        } else {
            Application.Run(new Form2());
         }
    }

Windows API を使って調べる

GetAsyncKeyState 関数 を使う
下の例は、Timerイベントで*キーを押し続けたかどうかを判定する方法

[DllImport("coredll.dll", SetLastError = true)]
private static extern Int16 GetAsyncKeyState(int vKey);

// winuser.hで定義されている
const int VK_F10 = 0x79;        // F10 キー
const int VK_F11 = 0x7A;        // F11 キー
const int VK_MULTIPLY = 0x6A;   // * キー

/// <summary>
/// 前回のタイマーイベントでの*キーの状態
/// </summary>
private short _OldKeyState = 0;
/// <summary>
/// キーを押し続けているどうかの状態
/// キーを押し続けていた場合、true。押し続けていない場合、false。
/// </summary>
private bool _IsRepeated = false;

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        short state = GetAsyncKeyState(VK_MULTIPLY);
        System.Diagnostics.Debug.WriteLine("VK_MULTIPLY : state=" + state.ToString("x"));
        if ((state & 0x8000) != 0)
        {
            if ((_OldKeyState & 0x8000) != 0)
            {
                // 前回の呼び出しから押し続けている
                _IsRepeated = true;
            }
            System.Diagnostics.Debug.WriteLine("[Startup]_IsMenu = " + _IsMenu);
        }

                _OldKeyState = state;
            }
    catch
    {
    }
}
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8