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

來源:互聯網
上載者:User
此時希望使用者不能通過鍵盤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)
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.