c# - 如何创建在尝试打开另一个实例时恢复打开窗口的单实例 WPF 应用程序?

标签 c# wpf

<分区>

抱歉,标题很难理解。我不知道该如何表达。

我有一个应用程序,每个用户 session 只允许运行一个实例。 如果用户再次单击以启动应用程序,我希望将已经聚焦的应用程序置于焦点位置。

窗口可能会折叠 Visibility。

如果它可见,我知道我可以使用

if (IsIconic(hWnd))
{
    ShowWindowAsync(hWnd, swRestore);
}

SetForegroundWindow(hWnd);

但是如果窗口折叠了,我有办法让它恢复可见吗?

最佳答案

您正在寻找 Mutex Class .它相当复杂,但幸运的是单例模式已被广泛讨论。有几篇关于它的好文章,但您可以在 C# .NET Single Instance Application 中找到它的一个很好的实现。 Sanity Free Coding 网站上的页面。从链接页面:

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    static void Main() {
        if(mutex.WaitOne(TimeSpan.Zero, true)) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            mutex.ReleaseMutex();
        } else {
            MessageBox.Show("only one instance at a time");
        }
    }
}

现在您可能想知道如何在 WPF 应用程序中使用 Main 方法,对吧?好吧,您必须做一些事情,但这并不困难。查看Writing a custom Main() method for WPF applications文章详细解释了这一点。来自那篇文章:

You basically need to change the application’s build action from “Application Definition” to “Page”, create a constructor that calls “InitializeComponent”, and write your Main() by eventually calling one of the application’s “Run” method overloads. ... Don’t forget, also, to remove the “StartupUri” from the App.xaml, otherwise another copy of window will show up (unless you get an error because the URI points to a non existing XAML resource).

因此,通过合并这两个资源,我们可以看到您的 App.xaml.cs 文件应该如下所示:

public partial class App : Application
{
    private static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    private static MainWindow mainWindow = null;

    App()
    {
        InitializeComponent();
    }

    [STAThread]
    static void Main()
    {
        if(mutex.WaitOne(TimeSpan.Zero, true)) 
        {
            App app = new App();
            mainWindow = new MainWindow();
            app.Run(mainWindow);
            mutex.ReleaseMutex();
        }
        else
        {
            mainWindow.WindowState = WindowState.Normal;
        }
    }
}

关于c# - 如何创建在尝试打开另一个实例时恢复打开窗口的单实例 WPF 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21789899/

相关文章:

c# - datagrid 获取单元格索引

WPF 网格大小自动与星形

c# - 数据绑定(bind)到 C# 中的对象

c# - 保留动态 "info"对象的最佳方法是什么,C#/.Net MVC/SQL Server 2008?

c# - 如何在不显式转换的情况下在内部调用显式接口(interface)实现方法?

C# - WPF - 在不使用 System.Windows.Forms 的情况下获取文件夹浏览器对话框?

c#-tesseract 以数字获取空间识别

C# DataGrid 更新所有行

c# - 在 WPF 中渲染 UIElement 期间等待屏幕

wpf - 添加项目后 DataGrid 刷新自身时索引 ArgumentOutOfRangeException