LoginSignup
2
2

More than 5 years have passed since last update.

.NET(C#)でALT+Tabを無効化する

Last updated at Posted at 2015-07-16

.NET(C#)でALT+Tabを無効化する方法です。
WindowsAPIのRegisterHotKeyを使用し、ALT+Tabをホットキーとして登録することで無効化します。
コードを以下のように記述します。

Form1.cs
namespace KeyboardIgnore
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        extern static int RegisterHotKey(IntPtr hWnd, int id, uint vkModifiers, uint vk);

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

        private const int HOTKEY_ID1 = 0x0001;
        private const int HOTKEY_ID2 = 0x0002;
        private const int MOD_ALT = 0x0001;
        private const int MOD_CONTROL = 0x0002;
        private const int MOD_SHIFT = 0x0004;
        private const int MOD_WIN = 0x0008;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // ホットキーの登録
            RegisterHotKey(this.Handle, HOTKEY_ID1, MOD_ALT, (uint)Keys.Tab);
            RegisterHotKey(this.Handle, HOTKEY_ID2, MOD_ALT | MOD_SHIFT, (uint)Keys.Tab);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // ホットキーの登録解除
            UnregisterHotKey(this.Handle, HOTKEY_ID1);
            UnregisterHotKey(this.Handle, HOTKEY_ID2);
        }
    }
}

なお、Windows7の場合は視覚スタイルを無効にしておかないとRegisterHotKeyが失敗するようです。
私はここで結構ハマったのでご注意ください。:joy:
1.スタート
2.コンピュータを右クリック
3.プロパティ
4.システムの詳細設定(画面左側)
5.詳細設定タブ(システムのプロパティ)
6.パフォーマンスの「設定」をクリック
7.視覚効果タブ(パフォーマンス オプション)
8.「ウィンドウとボタンに視覚スタイルを使用する」のチェックを外す

2
2
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
2
2