Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created October 18, 2013 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nissuk/7044239 to your computer and use it in GitHub Desktop.
Save nissuk/7044239 to your computer and use it in GitHub Desktop.
IMassageFilterでボタン押下を無効化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
/// <summary>
/// ボタン押下の操作をフィルタリングするクラスです。
/// </summary>
public class ButtonClickFilter : IMessageFilter
{
/// <summary>通常キー押下</summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>マウス左ボタンクリック</summary>
private const int WM_LBUTTONDOWN = 0x201;
/// <summary>マウス左ボタンダブルクリック</summary>
private const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// ボタン押下の操作をフィルタリングします。
/// </summary>
/// <param name="m">ディスパッチされるメッセージ。このメッセージは変更できません。</param>
/// <returns>true の場合、メッセージはフィルタで排除され、ディスパッチされません。false の場合、メッセージは次のフィルタまたはコントロールに継続されます。</returns>
public bool PreFilterMessage(ref Message m)
{
bool clickOrEnter
= m.Msg == WM_LBUTTONDOWN
|| m.Msg == WM_LBUTTONDBLCLK
|| (m.Msg == WM_KEYDOWN && (Keys)m.WParam == Keys.Enter);
// クリック/ダブルクリック時でもENTERキー押下時でもない場合、処理しません。
if (!clickOrEnter) return false;
Control control = Control.FromHandle(m.HWnd);
// 対象コントロールが取得できない場合、処理しません。
if (control == null) return false;
// 対象コントロールがボタンでない場合、処理しません。
if (!(control is Button)) return false;
// 何らかの処理...
MessageBox.Show("今はボタンを押さないで下さい…");
// trueでメッセージをフィルタ
return true;
}
}
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
// フィルタ追加
Application.AddMessageFilter(new ButtonClickFilter());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment