SoFunction
Updated on 2025-05-12

Using C# to achieve desktop locking effect of Window system

Preface

In actual development, we sometimes need to achieve "screen locking" effects, such as for demonstration programs, temporary permission control, or personal interest projects.

As a powerful desktop application development language, C# can easily implement this feature by combining it with Windows API.

This article will be called bySetForegroundWindowandGetForegroundWindowTwo core methods implement a simple but practical screen lock program and support entering the correct password to unlock. In addition, in order to improve the interactive experience, real-time mobile animation effects are also added to the password panel.

Functional Overview

This program has the following core functions:

1. Lock the entire screen immediately after startup to prevent users from switching to other applications;

2. Enter the correct password (default is 123456) to unlock;

3. The password input box area has a dynamic movement effect, which increases fun and visual appeal;

4. The interface has no border and translucent design, simulating the real lock screen style.

*Note: Since screenshots cannot be taken after running, the article does not include the running renderings. It is recommended that readers run the code in person to view the effect.

Technical points

1. Get and set the front desk window

We use two important Windows API methods to implement window mandatory focus:

GetForegroundWindow()

Function: Get the window handle that is currently active in the foreground.

Return value type:IntPtr

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

SetForegroundWindow(IntPtr hWnd)

Function: Set the specified window as the foreground window and get focus.

Parameter description:hWndis the handle to the target window.

Return value:truesuccess;falseFailed (such as the window is not visible or the permissions are insufficient)

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

These two functions are used in conjunction with a timer to continuously detect and force the user to stay on our locked window.

2. Program initialization settings

Complete the following configuration in the form load event:

private void FrmLockScreen_Load(object sender, EventArgs e)
{
     += FrmLockScreen_Activated;
     = ; // Full screen display     = 0.5D; // Translucent effect     = true; // Always top     = ; // Borderless     = new Point(( - 400) / 2,
                              ( - 300) / 2); // Center display}

Set the form to a maximum full screen, borderless, translucent, simulate the lock screen background;

The password input box is displayed in the center;

Add Enter key to listen for easy and quick unlocking.

3. Timely detection and force switch back to the locked window

We useEvery 100ms, check whether the current foreground window is our own program. If not, force switch back:

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

This can effectively prevent users from switching windows through Alt+Tab or clicking on the taskbar.

4. Dynamic mobile password panel

To make the interface more interesting, we added a simple motion animation to the password panel:

private void TimerMove_Elapsed(object sender, ElapsedEventArgs e)
{
    (new Action(() =>
    {
        int newX =  + speedX;
        int newY =  + speedY;

        // Boundary rebound logic        if (newX <= 0 || newX +  >= )
            speedX = -speedX;

        if (newY <= 0 || newY +  >= )
            speedY = -speedY;

         = new Point(newX, newY);
    }));
}

Use the timer to update the location every 30ms;

When the boundary automatically rebounds, it will form a "pinball" effect similar to it;

Enhance visual appeal and avoid the interface being too monotonous.

Complete code example

The following is the complete form class code:

public partial class FrmLockScreen : Form
{
    private  timer;
    private  timerMove;
    private int speedX = 2;
    private int speedY = 1;

    public FrmLockScreen()
    {
        InitializeComponent();
    }

    private void FrmLockScreen_Load(object sender, EventArgs e)
    {
         += FrmLockScreen_Activated;
         = ;
         = 0.5D;
         = true;
         = ;
         = new Point(
            ( - 400) / 2,
            ( - 300) / 2);

         = ;
        this.tbx_Password.KeyDown += FrmLockScreen_KeyDown;

        timer = new ();
         = 100;
         += Timer_Tick;
        ();

        timerMove = new ();
         = 30;
         += TimerMove_Elapsed;
        ();
    }

    private void FrmLockScreen_KeyDown(object sender, KeyEventArgs e)
    {
        if ( == )
        {
            UnlockButton_Click(this, null);
        }
    }

    private void TimerMove_Elapsed(object sender,  e)
    {
        (new Action(() =>
        {
            int newX =  + speedX;
            int newY =  + speedY;

            if (newX <= 0 || newX +  >= )
                speedX = -speedX;

            if (newY <= 0 || newY +  >= )
                speedY = -speedY;

             = new Point(newX, newY);
        }));
    }

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

    private void FrmLockScreen_Activated(object sender, EventArgs e)
    {
        SetForegroundWindow();
    }

    private void UnlockButton_Click(object sender, EventArgs e)
    {
        if (tbx_Password.Text == "123456")
        {
            ();
            ();
            ();
        }
        else
        {
            ("Error password");
        }
    }

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

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

Summarize

Through this article, we have mastered how to use C# combined with Windows API to implement a simple screen lock program, and maintain a locked state through the timer mechanism to prevent users from switching windows.

The main knowledge points include:

  • useSetForegroundWindowandGetForegroundWindowControl window focus;

  • Use timers to realize dynamic behavior and window monitoring;

  • Use WinForm's form properties to create a system lock screen effect;

  • Provide password verification mechanism to enhance security.

Although this project is small, it covers multiple practical skills, suitable for training programs for beginners in C#, and is also suitable for advanced development and expansion of more functions, such as:

Add graphic verification code;

Supports multi-user login;

More complex UI animations;

Logging and error prompts, etc.

at last

This is the end of this article about using C# to achieve desktop locking effect of Window system. For more related C# Window desktop locking content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!