C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# Window桌面锁定

利用C#实现Window系统桌面锁定效果

作者:小码编匠

在实际开发中,我们有时需要实现类似"屏幕锁定"的效果,C# 作为一门强大的桌面应用开发语言,结合 Windows API 可以轻松实现这一功能,所以本文将通过调用 SetForegroundWindow 和 GetForegroundWindow 两个核心方法,实现一个简易但实用的屏幕锁定程序,需要的朋友可以参考下

前言

在实际开发中,我们有时需要实现类似"屏幕锁定"的效果,比如用于演示程序、临时权限控制、或者个人兴趣项目。

C# 作为一门强大的桌面应用开发语言,结合 Windows API 可以轻松实现这一功能。

本文将通过调用 SetForegroundWindowGetForegroundWindow 两个核心方法,实现一个简易但实用的屏幕锁定程序,并支持输入正确密码解锁。此外,为了提升交互体验,还为密码面板增加了实时移动动画效果。

功能概述

该程序具备以下核心功能:

1、启动后立即锁定整个屏幕,阻止用户切换到其他应用程序;

2、输入正确密码(默认为 123456)可解除锁定;

3、密码输入框区域具有动态移动效果,增加趣味性和视觉吸引力;

4、界面无边框、半透明设计,模拟真实锁屏风格。

*注意:由于运行后无法截图,因此文中不附运行效果图,建议读者亲自运行代码查看效果。

技术点

1、获取与设置前台窗口

我们使用了两个重要的 Windows API 方法来实现窗口强制聚焦功能:

GetForegroundWindow()

作用:获取当前处于前台活动状态的窗口句柄。

返回值类型:IntPtr

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

SetForegroundWindow(IntPtr hWnd)

作用:将指定窗口设为前台窗口,并获得焦点。

参数说明:hWnd 是目标窗口的句柄。

返回值:true 成功;false 失败(如窗口不可见或权限不足)

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

这两个函数结合定时器使用,可以持续检测并强制用户停留在我们的锁定窗口上。

2、程序初始化设置

在窗体加载事件中完成以下配置:

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 = FormBorderStyle.None; // 无边框
    this.Location = new Point((Screen.PrimaryScreen.Bounds.Width - 400) / 2,
                              (Screen.PrimaryScreen.Bounds.Height - 300) / 2); // 居中显示
}

设置窗体为最大全屏、无边框、半透明,模拟锁屏背景;

密码输入框居中显示;

添加回车键监听,方便快速解锁。

3、定时检测并强制切回锁定窗口

我们使用 System.Timers.Timer 每隔 100ms 检测一次当前前台窗口是否是我们自己的程序,如果不是,则强制切回来:

private void Timer_Tick(object sender, EventArgs e)
{
    this.Invoke(new Action(() =>
    {
        if (GetForegroundWindow() != this.Handle)
        {
            SetForegroundWindow(this.Handle);
        }
    }));
}

这样可以有效防止用户通过 Alt+Tab 或点击任务栏切换窗口。

4、动态移动密码面板

为了让界面更有趣味性,我们给密码面板添加了一个简单的运动动画:

private void TimerMove_Elapsed(object sender, 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);
    }));
}

使用定时器每 30ms 更新一次位置;

遇到边界自动反弹,形成类似"弹球"效果;

增强视觉吸引力,避免界面过于单调。

完整代码示例

以下是完整的窗体类代码:

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 = FormBorderStyle.None;
        this.Location = new 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("密码错误");
        }
    }

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();
}

总结

通过本文的学习,我们掌握了如何利用 C# 结合 Windows API 来实现一个简单的屏幕锁定程序,并通过定时器机制保持锁定状态,防止用户切换窗口。

主要知识点包括:

该项目虽然小巧,但涵盖了多个实用技巧,适合作为 C# 初学者的练手项目,也适合进阶开发拓展更多功能,例如:

加入图形验证码;

支持多用户登录;

更加复杂的 UI 动画;

日志记录与错误提示等。

最后

到此这篇关于利用C#实现Window系统桌面锁定效果的文章就介绍到这了,更多相关C# Window桌面锁定内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文