程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# Winform 實現屏蔽鍵盤的win和alt+F4的實現代碼

C# Winform 實現屏蔽鍵盤的win和alt+F4的實現代碼

編輯:C#基礎知識
此時希望用戶不能通過鍵盤alt+F4來結束程序及通過Win的組合鍵對窗口進行操作。我在網上搜索了一下,采用全局鍵盤鉤子的方法可以做到屏蔽用戶對鍵盤的操作。。以下為相關代碼,用到了Form1_load事件和Form1_FormClosing事件:
代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace WindowsApplication10
{
public partial class Form1 : Form
{
// 安裝鉤子
[DllImport("user32.dll")]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
// 卸載鉤子
[DllImport("user32.dll")]
public static extern bool UnhookWindowsHookEx(int idHook);
// 繼續下一個鉤子
[DllImport("user32.dll")]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
//聲明定義
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
static int hKeyboardHook = 0;
HookProc KeyboardHookProcedure;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
HookStart();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
HookStop();
}
// 安裝鉤子
public void HookStart()
{
if (hKeyboardHook == 0)
{
// 創建HookProc實例
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//定義全局鉤子
hKeyboardHook = SetWindowsHookEx(13, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
if (hKeyboardHook == 0)
{
HookStop();
throw new Exception("SetWindowsHookEx failed.");
}
}
}
//鉤子子程就是鉤子所要做的事情。
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//這裡可以添加別的功能的代碼
return 1;
}
// 卸載鉤子
public void HookStop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
if (!(retKeyboard)) throw new Exception("UnhookWindowsHookEx failed.");
}
}
}

(注:該方法可以屏蔽win和alt+F4但是不能屏蔽ctrl+alt+del)
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved