Ivan
Ivan

Reputation: 64207

How to bring a form already shown up to the very foreground and focus it?

How to programmatically (assuming we've got a reference to it as a variable) bring a form already shown up to the very foreground and focus it in a C# WinForms application?

Upvotes: 3

Views: 2922

Answers (5)

Waleed
Waleed

Reputation: 3145

You should use the BringToFront() method

Upvotes: 3

Nick Olsen
Nick Olsen

Reputation: 6369

The answers here didn't quite do it for me. Using BringToFront wouldn't actually bring it to the front if the form was not focused and using Form.Activate just makes the form flash if it doesn't have focus. I wrote this little helper and it works flawlessly (I can't take total credit, found this somewhere on the web for WPF and converted it):

public static class FormHelper
    {
        const UInt32 SWP_NOSIZE = 0x0001;
        const UInt32 SWP_NOMOVE = 0x0002;
        const UInt32 SWP_SHOWWINDOW = 0x0040;

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

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("User32")]
        private static extern int SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        [DllImport("user32.dll")]
        private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        public static void BringToFront(Form form)
        {
            var currentForegroundWindow = GetForegroundWindow();
            var thisWindowThreadId = GetWindowThreadProcessId(form.Handle, IntPtr.Zero);
            var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);
            SetWindowPos(form.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);
            form.Show();
            form.Activate();
        }
    }

All you have to do is call FormHelper.BringToFront passing in the form you want to be shown.

Upvotes: 2

Bala R
Bala R

Reputation: 108937

Have you tried Form.Show() and/or Form.BringToFront() ?

Upvotes: 0

nirmus
nirmus

Reputation: 5093

Form.Show();

or

Form.ShowDialog();

What's different? First show new form but all other will be activity. Second solution make that only this new form will be activity.

Upvotes: 0

Alex Aza
Alex Aza

Reputation: 78447

You can use SetForegroundWindow. Good example here: C# Force Form Focus.

[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

Usage:

SetForegroundWindow(form.Handle);

Upvotes: 7

Related Questions