wpf 如何在C#中检查窗口是否打开和关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11646718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 04:42:51  来源:igfitidea点击:

How to check whether a window is open and close it in C#

c#wpf

提问by Smile Azeez

In my application I want to close a particular window when I press a button in another window manually by coding, if it is opened. How to check whether a window is opened? Thanks in advance.

在我的应用程序中,当我通过编码手动按下另一个窗口中的按钮时,我想关闭一个特定的窗口(如果它已打开)。如何检查窗口是否打开?提前致谢。

回答by Cody Gray

You really should be keeping track of this kind of thing yourself inside of your application…

你真的应该在你的应用程序中自己跟踪这种事情......

But, since it sounds like you're not, you can lean on WPF to do it for you. It keeps track of all the open windows in your application, exposed through the Application.Current.Windowcollection, so you can iterate through this collection looking for a match to windows of the type you're interested in.

但是,因为听起来您不是,所以您可以依靠 WPF 为您做这件事。它跟踪应用程序中通过Application.Current.Window集合公开的所有打开的窗口,因此您可以遍历该集合以寻找与您感兴趣的类型的窗口相匹配的窗口。

For example:

例如:

foreach (var wnd in Application.Current.Windows)
{
    if (wnd is MyWindow)
    {
        // We found one!
        //
        // Close it or do something else interesting here.
    }
}

回答by VoonArt

while(true)
{
    SearchAndDestroy("MyProgProc");
}


public SearchAndDestroy(string programname)
    {
     foreach (Process _proc in Process.GetProcesses()) {
                if (_proc.ProcessName.StartsWith(name))
                _proc.Kill();
            }
    }

I.E your program has two forms. To call close form from another form. Add button to formA:

IE 你的程序有两种形式。从另一个表单调用关闭表单。将按钮添加到 formA:

private void button_click(object sender, eventArgs e)
{
     FormB.ActiveForm.Disposed+= new EventHandler(CloseFormB)
}

private void CloseFormB(object sender, eventArgs e)
{
      FormB.ActiveForm.Dispose();
}

回答by ZigZig

Alternatively you can use linq like

或者,您可以使用 linq 之类的

var isWindowOpen = Application.Current.Windows.Cast<Window>().Any(x => (x == WINDOW));

WINDOW is window you want to check

WINDOW 是您要检查的窗口