Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't consistently bring form to front

Tags:

c#

forms

winforms

I've tried several things, but none of them work...

I have Form that should come in front of all Windows on clicking NotifyIcon. So here is what I tried:

private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        this.TopMost = true;
        this.BringToFront();
        this.Focus();
        this.TopMost = false;
    }
}

Then I tried to use SetForegroundWindow:

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern bool SetForegroundWindow(IntPtr hwnd);

by adding

        SetForegroundWindow(this.Handle);

at the end of the if block.

Finally, I saw that when this doesn't work if I click right mouse button on NotifyIcon and context menu gets opened, I can then left click NotifyIcon and it brings it to the front.

I've tried to add this code at the beginning:

        cmsNotifyIcon.Show();
        cmsNotifyIcon.Close();

So that it shows and closes notifyIcon context menu, as a possible idea for workaround, but it doesn't help.

Any ideas on how to do this, or work around this?

like image 631
Ivan Ičin Avatar asked Jan 06 '10 15:01

Ivan Ičin


2 Answers

what if you do it on MouseUp ?

like image 131
Catalin DICU Avatar answered Oct 17 '22 00:10

Catalin DICU


Here's how I've done it. Note that StartupWindowState and HideWhenMinimized are a private members of my form.

private void OnOpenTrayMenuItemClicked(object sender, EventArgs e) {
    if (this.WindowState == FormWindowState.Minimized) {
        this.WindowState = this.StartupWindowState;
        this.ShowInTaskbar =
            (this.HideWhenMinimized && (this.WindowState == FormWindowState.Minimized)) ? false : true;
        this.Show();
    }

    this.Activate();
}
like image 3
Matt Davis Avatar answered Oct 17 '22 00:10

Matt Davis