简体   繁体   English

请参阅WPF中的活动窗口?

[英]Refer to active Window in WPF?

如何使用WinForms中的ActiveForm属性来引用C#中的活动Window of WPF应用程序?

One possible way would be to scan the list of open windows in the application and check which one of them has IsActive = true : 一种可能的方法是扫描应用程序中打开的窗口列表,并检查其中哪一个具有IsActive = true

Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

Not sure if there may be more than one active window if, for example, there's a modal dialog showing, in which case, the owner of the dialog and the dialog itself might be active. 例如,如果显示模式对话框,则不确定是否存在多个活动窗口,在这种情况下,对话框的所有者和对话框本身可能处于活动状态。

There is better way to do this using PInvoke. 使用PInvoke有更好的方法。 Aviads answer is not working all the time (there are some edge cases with dialogs). Aviads答案不是一直有效(有一些边缘情况有对话框)。

IntPtr active = GetActiveWindow();

ActiveWindow = Application.Current.Windows.OfType<Window>()
    .SingleOrDefault(window => new WindowInteropHelper(window).Handle == active);

One must include following import first: 首先必须包括以下导入:

[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

I have problems With this way "Application.Current.Windows.OfType().SingleOrDefault(x => x.IsActive);" 我有这样的问题“Application.Current.Windows.OfType()。SingleOrDefault(x => x.IsActive);” specialy because I was building an aplication with a main Window then i had problems when the main window was selected. 特别是因为我正在使用主窗口构建应用程序,然后在选择主窗口时出现问题。 I resolve it creating this: 我决定创建它:

In some base class or App.xaml.cs create this: 在某些基类或App.xaml.cs中创建:

       public static Window ActivatedWindow {get;set;}

Then put in your base class deriving Window or all of your Window's Activate Event: 然后输入您的基类派生窗口或所有Window的Activate事件:

First Option - personal Window Base Class: 第一选择 - 个人窗口基类:

       public class MetroToolWindowBase
       {
         public MetroToolWindowBase()
         {   
            Activated += new EventHandler(MakeActive); 
         }   
         private void MakeActive(object sender, EventArgs e)
         {
        App.ActivatedWindow= this;
         }
       }

Second Option- In Activated Event of Windows: 第二个选项 - 在Windows的激活事件中:

   private void XWindow_Activated(object sender,EventArgs e)
    {
     App.ActivatedWindow= this;
    }

I know this is a bit old question but I think my answer could help someone. 我知道这是一个有点老问题,但我认为我的答案可以帮助某人。

My problem was this: I had a WPF MVVM application and I needed to get my MainWindow instance in the second view, ie second view model, in order to set the visibility of title bar button to visible . 我的问题是:我有一个WPF MVVM应用程序,我需要在第二个视图中获取我的MainWindow实例,即第二个视图模型,以便将标题栏按钮的可见性设置为visible

This is my solution: 这是我的解决方案:

MainWindow window = (MyApp.MainWindow)App.Current.MainWindow;
window.btnSearch.Visibility = System.Windows.Visibility.Visible;

Hope this would help someone. 希望这会对某人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM