抱歉,标题很难理解。我不知道该如何表达。
我有一个应用程序,每个用户 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;
}
}
}