WPF:即使显式设置WindowState,窗口也会保持最小化 [英] WPF: Window stays minimized even when setting WindowState explicitly

查看:367
本文介绍了WPF:即使显式设置WindowState,窗口也会保持最小化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一个托盘图标,双击该图标可隐藏或显示应用程序窗口.我的问题是,如果窗口在隐藏时处于最小化状态,则似乎无法将其置于前景.

My application has a tray icon which, when double-clicked, hides or shows the application window. My issue is that I can't seem to bring the window to the foreground if it was in a minimized state when it was hidden.

例如,假设用户将应用程序最小化,然后双击任务栏图标.然后,应用程序窗口被隐藏,并从任务栏中消失.当用户再次双击任务栏图标时,应出现应用程序窗口,即应从最小化状态还原并显示到前台.

For instance, say the user minimizes the application and then double-clicks the tray icon. The application window is then hidden and disappears from the taskbar. When the user double-clicks the tray icon again, the application window should appear, i.e. it should be restored from the minimized state and brought to the foreground.

下面的代码应该这样做,但是由于某些原因,它不能:

The code below ought to do just that, but for some reason it doesn't:

private void TrayIcon_DoubleClick(object sender, EventArgs e)
{
    if (this.Visibility == Visibility.Hidden)
    {
        this.Visibility = Visibility.Visible;
        this.WindowState = WindowState.Normal;
        this.Activate();
    }
    ...
}

该应用程序保持最小化,并且不会成为前台. Activate()返回true,随后对 TrayIcon_DoubleClick()的调用表明状态确实设置为 Normal .

The application stays minimized and isn't brought to the foreground. Activate() returns true and subsequent calls to TrayIcon_DoubleClick() indicate that the state is indeed set to Normal.

推荐答案

我在MSDN论坛和

I cross posted my question on the MSDN Forums and it got answered there. To quote the answer:

Window上的某些属性更像方法,从某种意义上说,它们会导致发生复杂的动作,需要在上一个动作已经完成之后进行.实现该目标的一种方法是使用Dispatcher.BeginInvoke.如果将代码更改为如下所示,它应该可以工作:

Some properties on Window that are more like methods, in the sense they cause complex actions to happen, need to happen after the previous action has already completed. One way to get that to happen is using Dispatcher.BeginInvoke. If you change your code to look like this, it should work:

if (this.Visibility == Visibility.Hidden)
{
    this.Visibility = Visibility.Visible;
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
        new Action(delegate()
        {
            this.WindowState = WindowState.Normal;
            this.Activate();
        })
    );
}

我尝试了一下,它为我解决了问题.另外,我认为您也可以省略this.Activate().

I tried this out and it fixed the problem for me. Also, I think you can leave out the this.Activate() as well.

这篇关于WPF:即使显式设置WindowState,窗口也会保持最小化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆