How to bring the form already shown to the fore and focus it?

How programmatically (provided that we have a link to it as a variable), a form has appeared, already shown in the foreground, and focus it in a C # WinForms application?

+3
source share
5 answers

You must use the method BringToFront()

+3
source

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

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

Using:

SetForegroundWindow(form.Handle);
+7
source

. BringToFront , . flash, . , ( , - WPF ):

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();
        }
    }

, , FormHelper.BringToFront, , .

+2
Form.Show();

Form.ShowDialog();

? , . , .

0

All Articles