I have C# windows form application, with all default settings. I am using VS 2008, OS - Windows VIsta.

When my form loses focus, (as in when a user clicks on something behind the form), i need the same form that lost focus to regain it.

I made use of this Event to handle this;

private void Form1_Deactivate_1(object sender, EventArgs e)
    {
    
      Console.WriteLine("DEACTIVATE EVENT _______+++++++++_________");
       Form1 f = new Form1();
      f.show();
    }

Here, what you will see is that is when the form loses its focus, the Console.writeline command will execute and a new form will appear on the screen. I do not want this. i want the exact form that lost focus to regain focus and appear back on the screen. How do i do this.

Dani AI

Generated

Short answer: Windows will not let a normal desktop app keep “stealing” the keyboard/foreground from another process. Making the form TopMost only keeps it visually on top; it does not (and cannot reliably) force the OS to keep keyboard focus on your window. (learn.microsoft.com)

Practical guidance (safe → hacky):

  • Best: rework the UX so you do not need to fight the OS. If the goal is to force users to finish a task inside your app, use a modal dialog (ShowDialog) or build a kiosk/assigned‑access experience instead of trying to steal focus.
  • If you only need to draw attention, flash the taskbar or show a notification rather than forcing focus.
  • If you absolutely must attempt to programmatically bring your window back you can try Win32 calls (AttachThreadInput + SetForegroundWindow/BringWindowToTop + ShowWindow). This is a workaround and still subject to the OS focus rules (LockSetForegroundWindow / foreground lock timeout / other conditions); it may fail and behaves differently while debugging. (learn.microsoft.com)

Example (last‑resort P/Invoke helper — call it from the UI thread and avoid spawning new Form instances inside Deactivate):

// call: this.BeginInvoke(new Action(() => FocusHelper.ForceForeground(this.Handle)));

public static class FocusHelper
{
    const int SW_RESTORE = 9;

    [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr hWnd);
    [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
    [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
    [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);
    [DllImport("user32.dll")] static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

    public static void ForceForeground(IntPtr hWnd)
    {
        if (hWnd == IntPtr.Zero) return;
        IntPtr fg = GetForegroundWindow();
        if (fg == hWnd) { SetForegroundWindow(hWnd); return; }

        uint fgThread = GetWindowThreadProcessId(fg, out _);
        uint myThread = GetCurrentThreadId();

        if (AttachThreadInput(myThread, fgThread, true))
        {
            BringWindowToTop(hWnd);
            ShowWindow(hWnd, SW_RESTORE);
            SetForegroundWindow(hWnd);
            AttachThreadInput(myThread, fgThread, false);
        }
        else
        {
            ShowWindow(hWnd, SW_RESTORE);
            BringWindowToTop(hWnd);
            SetForegroundWindow(hWnd);
        }
    }
}

Notes and cautions: creating a brand new Form in Deactivate (as in the original post) just makes a second window and does not solve focus rules. As suggested, Form.Activate exists, but it won’t override the OS restrictions for cross‑process focus changes; the Win32 docs explain when SetForegroundWindow is permitted and when it will fail. Test behavior on release builds (debugging can change permissions). (learn.microsoft.com)

If staying focused across user clicks is a hard requirement, consider redesigning for kiosk mode / replacing the shell rather than fighting the platform.

Recommended Answers

All 11 Replies

Why do you want to mix a Console and a Forms application?

Why do you want to mix a Console and a Forms application?

that's just for testing purposes. it will be removed later. and i guess that it won't have any effect to what i am trying to achieve.

i need the same form that lost focus to regain it.

What exactly do you mean?
When you click another application window, your form deactivates and looses focus, when you click on your form it activates again and regains focus.

What exactly do you mean?
When you click another application window, your form deactivates and looses focus, when you click on your form it activates again and regains focus.

Just imagine like this. You open a browser page (which occupies the whole screen). the you execute your windows form application (which is 5X5 CM). Now the form application is on focus.

You set a few properties in your form application to always stay on top. (TopMost)

now when you click in the browser, the form application will lose focus (but remain on top because the TopMost property is set). What i want to do is, when any user, at all circumstance click something back of the screen, the form application should not lose focus and it should always be on top, with focus set on it.

hope i made it clear :S

So you want something like a modeless dialog?
Like a Find dialog you can keep on top all the time?
Well you always have to click it to get its "attention".
It's like driving two cars, you cannot drive both at the same time.

So you want something like a modeless dialog?
Like a Find dialog you can keep on top all the time?
Well you always have to click it to get its "attention".
It's like driving two cars, you cannot drive both at the same time.

Yes something like that, but i don't want to click on anything, it should automatically be on focus.

Hope you have seen some websites, when you try to close it it pops up asking if you want to remain in the same page or leave it. at least something like that would do. and focus should be back on the form

Sorry, I'm out of resources here.:(

Sorry, I'm out of resources here.:(

yup its ok. By any chance do you know how to access the MouseClick event in VS 2008. Its not there in the list provided. How do i add this event ? (i know its a new question, but if you know could you tell me how to do it)

Yes, you had better posted this question in a new thread. :S
But a Form has a MouseClick event!
Create a formsapp.
In the properties window of the form, select the events button(the one with the lightning bolt).
Find the MouseClick event, double click it and you are ready to code it!

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.