4

我正在使用 WPF(C#) 编写程序。我使用这样的方法来打开和关闭窗口:

public static void openCloseWindow(Window toBeOpen, Window toBeClose)
{
    toBeOpen.Show();

    makeWindowCenter(toBeOpen);

    toBeClose.Close();
}

在程序的一部分我使用这种方法是这样的:

openCloseWindow(new BestCustomerWindow,this);

因此最终用户可以在一个按钮上单击多次,并且可以打开许多窗口。

有什么办法可以避免在运行时打开窗户?

了解更多信息:

让我点击一个打开 window1 的按钮。我想要:

  • 如果 window1 已关闭,请打开它。
  • 否则,如果打开了 window1,则关注 window1。
4

5 回答 5

12

替换WINDOWNAME为所需窗口的名称:

bool isWindowOpen = false;

foreach (Window w in Application.Current.Windows)
{
    if (w is WINDOWNAME)
    {
        isWindowOpen = true;
        w.Activate();
    }
}

if (!isWindowOpen)
{
    WINDOWNAME newwindow = new WINDOWNAME();
    newwindow.Show();
}
于 2013-08-15T02:44:14.683 回答
1

此代码将完全按照您的要求执行:

只需存储对话框对象并检查它是否已在 showWindow 中创建。

使用 windows Closed 事件清除对对话框对象的引用。

AddItemView dialog;

private void showWindow(object obj)
{

    if ( dialog == null )
    {
       dialog = new AddItemView();
       dialog.Show();
       dialog.Owner = this;
       dialog.Closed += new EventHandler(AddItemView_Closed);
    }
    else
       dialog.Activate();
}

void AddItemView_Closed(object sender, EventArgs e)
    {

        dialog = null;
    }

请注意,这个问题已经在这里问过了

于 2013-08-15T05:05:13.767 回答
1

阿巴德,

我认为您可以使用 Mutex,请参考以下代码(在 App.xaml.cs 文件中):

public partial class App : Application
{
    [DllImport("user32", CharSet = CharSet.Unicode)]
    static extern IntPtr FindWindow(string cls, string win);
    [DllImport("user32")]
    static extern IntPtr SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32")]
    static extern bool IsIconic(IntPtr hWnd);
    [DllImport("user32")]
    static extern bool OpenIcon(IntPtr hWnd);

    protected override void OnStartup(StartupEventArgs e)
    {
        bool isNew;
        var mutex = new Mutex(true, "My Singleton Instance", out isNew);
        if (!isNew)
        {
            ActivateOtherWindow();
            Shutdown();
        }
    }
    private static void ActivateOtherWindow()
    {
        var other = FindWindow(null, "MainWindow");
        if (other != IntPtr.Zero)
        {
            SetForegroundWindow(other);
            if (IsIconic(other))
                OpenIcon(other);
        }
    }
}
于 2013-08-15T02:49:30.870 回答
1

我写了一个基于@rhys-towey 答案的快速函数

    void OpenNewOrRestoreWindow<T>() where T : Window, new()
    {
        bool isWindowOpen = false;

        foreach (Window w in Application.Current.Windows)
        {
            if (w is T)
            {
                isWindowOpen = true;
                w.Activate();
            }
        }

        if (!isWindowOpen)
        {
            T newwindow = new T();
            newwindow.Show();
        }
    }

用法OpenNewOrRestoreWindow<SomeWindow>();

于 2019-11-07T16:29:00.593 回答
-1

只需使用

tobeopen.ShowDialog();    

例如我的窗口类名称是“Window1”使用“Window1.ShowDialog();”

如果窗口已经打开,它将不会打开并发出警报声。

于 2017-10-17T05:51:54.537 回答