在C# 中如何實現(xiàn)Windows 系統(tǒng)鎖定屏幕的效果,本文通過使用Windows API 中的設(shè)置前臺窗口方法SetForegroundWindow和獲取前臺窗口方法GetForegroundWindow方法實現(xiàn)。
SetForegroundWindow:是將指定的窗口(通過其句柄 hWnd)設(shè)置為前臺窗口,并激活它(即獲得焦點)。
方法簽名:
private static extern bool SetForegroundWindow(IntPtr hWnd);
IntPtr:hWnd 目標窗口的句柄。
return:true 成功設(shè)置窗口為前臺窗口。
return:false 失敗(可能由于權(quán)限不足或窗口不可見)。
GetForegroundWindow:的作用是獲取當前處于前臺活動狀態(tài)的窗口的句柄。
方法簽名:
private static extern IntPtr GetForegroundWindow();
IntPtr:hWnd 當前處于前臺活動狀態(tài)的窗口。
通過上面的方法僅是設(shè)置活動窗口,鎖定桌面。那么如何解除鎖定呢?最簡單的方式當然是通過按鈕關(guān)閉,但是又不能如此簡單,那就是加密碼判斷,所以需要添加按鈕和文本框,輸入正確的密碼解除鎖定。
為了更炫酷一點的,程序中還添加一個密碼面板區(qū)域?qū)崟r移動顯示效果。
1、程序運行鎖定屏幕。
2、輸入密碼解鎖屏幕。
3、初始密碼123456。
代碼
public partial class FrmLockScreen : Form
{
private System.Timers.Timer timer;
private System.Timers.Timer timerMove;
private int speedX = 2;
private int speedY = 1;
public FrmLockScreen()
{
InitializeComponent();
}
private void FrmLockScreen_Load(object sender, EventArgs e)
{
this.Activated += FrmLockScreen_Activated;
this.WindowState = FormWindowState.Maximized;
this.Opacity = 0.5D;
this.TopMost = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Location = new System.Drawing.Point(
(Screen.PrimaryScreen.Bounds.Width - 400) / 2,
(Screen.PrimaryScreen.Bounds.Height - 300) / 2);
this.panel.BackColor = SystemColors.Window;
this.tbx_Password.KeyDown += FrmLockScreen_KeyDown;
timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += Timer_Tick;
timer.Start();
timerMove = new System.Timers.Timer();
timerMove.Interval = 30;
timerMove.Elapsed += TimerMove_Elapsed;
timerMove.Start();
}
private void FrmLockScreen_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
UnlockButton_Click(this,null);
}
}
private void TimerMove_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
panel.Invoke(new Action(() =>
{
int newX = panel.Location.X + speedX;
int newY = panel.Location.Y + speedY;
if (newX <= 0 || newX + panel.Width >= this.ClientSize.Width)
speedX = -speedX;
if (newY <= 0 || newY + panel.Height >= this.ClientSize.Height)
speedY = -speedY;
panel.Location = new Point(newX, newY);
}));
}
private void Timer_Tick(object sender, EventArgs e)
{
this.Invoke(new Action(() =>
{
if (GetForegroundWindow() != this.Handle)
{
SetForegroundWindow(this.Handle);
}
}));
}
private void FrmLockScreen_Activated(object sender, EventArgs e)
{
SetForegroundWindow(this.Handle);
}
private void UnlockButton_Click(object sender, EventArgs e)
{
if (tbx_Password.Text == "123456")
{
timer.Stop();
timerMove.Stop();
this.Close();
}
else
{
MessageBox.Show("密碼錯誤");
}
return;
}
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
}
該案例通過強制某個窗口顯示在最前面(即便是其他程序窗口在運行)。通過定時器定時檢測當前活動窗口,判斷用戶是否試圖切換到其他窗口,如果是則強制切回鎖定窗口,達到鎖定屏幕的效果。
該文章在 2025/5/10 18:33:20 編輯過