I created a windows form application (using windows vista, MS visual studio 2008). This form only has a button and a textbox.

I need this form not to lose focus. for example when the form is on the screen, the user can click something that is behind the form, then the form will lose focus. So is there any way to programatically achieve this?

The form should always be on top (i have coded this using the topmost property), but yet i need the form to be focussed.

Another approach where we could code this as follows; When the form loses focus we could popup a message box (with Yes or No), when he clicks yes the Form will get back its focus.

Anyway i am clueless as in how to achieve this. can someone Help me

Dani AI

Generated

Short answer and practical options (builds on , and ): Windows will not reliably let an application “lock” input to itself — the OS intentionally limits which processes can steal the foreground. Use the Deactivate event as a polite gate, and only use Win32 calls as a fallback when necessary. ’s idea to call Focus() / Activate() is the right first step; the code below shows a stronger but not-guaranteed fallback that attempts to re-acquire the foreground window.

Try this pattern (wire Deactivate and attempt a polite then stronger activation):

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public partial class Form1 : Form
{
    [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);
    [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
    [DllImport("user32.dll")] static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

    public Form1()
    {
        InitializeComponent();
        this.Deactivate += Form1_Deactivate; // register event if designer not used
    }

    private void Form1_Deactivate(object sender, EventArgs e)
    {
        // polite attempt
        this.TopMost = true;
        this.Activate();

        // stronger attempt (may still be blocked by system policy)
        IntPtr fg = GetForegroundWindow();
        uint fgThread = GetWindowThreadProcessId(fg, out _);
        uint thisThread = GetCurrentThreadId();
        AttachThreadInput(thisThread, fgThread, true);
        SetForegroundWindow(this.Handle);
        AttachThreadInput(thisThread, fgThread, false);

        this.Focus();
    }
}

The functions used above are documented (see the SetForegroundWindow and AttachThreadInput references). (learn.microsoft.com)

Important caveats and alternatives: Windows enforces foreground rules (there is also AllowSetForegroundWindow, LockSetForegroundWindow and the foreground-lock timeout setting), so the stronger approach can fail and is generally discouraged for good UX. If the goal is to prevent accidental clicks behind the form, consider a modal dialog, a topmost overlay that blocks clicks, or a non-activating notification rather than repeatedly forcing focus — these approaches avoid fighting OS policies and reduce user frustration. See the platform docs for AllowSetForegroundWindow, LockSetForegroundWindow and the SPI_GETFOREGROUNDLOCKTIMEOUT setting. (learn.microsoft.com)

If keeping focus is a hard requirement, test on the exact Windows versions you target and prefer coordinated methods (the foreground-owning process enabling your process) rather than repeatedly stealing focus; that avoids flaky behavior and possible security/AV flags.

Recommended Answers

All 4 Replies

Its been a while sinced I used windows forms, but Im sure there is a LoseFocus event or something similar. In that event, just reset your focus using your window handle.

Edit: Here is a list of events available. http://msdn.microsoft.com/en-us/library/system.windows.forms.form_events.aspx

There is a Leave event. This triggers when the window loses focus. You would register this event for your main window and inside the event, reset focus to your program.

Edit #2: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

Its been a while sinced I used windows forms, but Im sure there is a LoseFocus event or something similar. In that event, just reset your focus using your window handle.

Edit: Here is a list of events available. http://msdn.microsoft.com/en-us/library/system.windows.forms.form_events.aspx

There is a Leave event. This triggers when the window loses focus. You would register this event for your main window and inside the event, reset focus to your program.

Edit #2: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

Ok i looked at Deactivate , seems promising, but how do i integrate it to my code.
i pasted the following code in

private void Form1_Deactivate(Object sender, EventArgs e) {

   MessageBox.Show("You are in the Form.Deactivate event.");

}

but how does the Program knows if to execute this method ? Any clue ?

You have to register it. I assume you are using Visual studio as an aid to build it instead of programming it? If so, there is an event's list which can be found in the form properties window. In it, find the event and double click it and it will automatically register the event for you.

Edit: As for keeping the focus on the form, simply call this.Focus();. This will not keep the form from going behind other windows though.

Perhaps a look at this code snippet will shine a light.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.