开发者

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?


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

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

Usage:

SetForegroundWindow(form.Handle);


You should use the BringToFront() method


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜