不能始终如一地把形式带到前面

时间:2010-01-06 15:11:26

标签: c# winforms forms

我尝试了几件事,但没有一件能奏......

我有单独NotifyIcon时应该出现在所有Windows前面的Form。所以这就是我的尝试:

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

然后我尝试使用SetForegroundWindow:

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

添加

        SetForegroundWindow(this.Handle);

在if块的末尾。

最后,当我在NotifyIcon上单击鼠标右键并打开上下文菜单时,我看到当这不起作用时,我可以左键单击NotifyIcon并将它带到前面。

我尝试在开头添加此代码:

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

这样它可以显示和关闭notifyIcon上下文菜单,作为解决方法的一个可能的想法,但它没有帮助。

有关如何执行此操作的任何想法,或解决此问题?

5 个答案:

答案 0 :(得分:5)

如果你在MouseUp上做了什么?

答案 1 :(得分:3)

这就是我如何做到的。请注意,StartupWindowStateHideWhenMinimized是我表单的私人成员。

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

答案 2 :(得分:1)

使用Activate()代替Show()。此外,如果您的表单最小化,您必须将其WindowState设置为WindowState.Normal(或在最小化之前的任何状态)。


        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            Activate();

            // this is needed for minimized form to show
            WindowState = FormWindowState.Normal;
        }

答案 3 :(得分:0)

我有类似的问题;一个简单的解决方法对我来说足够了。在我需要显示表单的事件处理程序中,我只是检查窗口是否可见/正常,如果是,则将其最小化。其余的代码然后重新启动它。

    private void OnDetails(object Sender, EventArgs Args)
    {
        if (DetailsForm == null)
        {
            DetailsForm = new MyForm(this);
        }

        if (DetailsForm.WindowState == FormWindowState.Normal)
            DetailsForm.WindowState = FormWindowState.Minimized;

        DetailsForm.WindowState = FormWindowState.Normal;
        DetailsForm.Show();
    }

答案 4 :(得分:0)

试试这个

这个功能对我有用:

public static void BringFormToFront(Form form) {

    form.Activate();
    form.TopMost = true;
    form.TopMost = false;
    form.Focus();
    form.BringToFront();

}

如果你想要更加懒惰:

public static void ShowFormToFront(Form form) {
    form.Show();
    BringFormToFront(form);
}

这些很容易extension methods