Sal*_*muk 4 c# single-instance ui-automation winforms
我刚刚实现了这段代码,该代码保护应用程序的单个实例,以免应用程序运行两次。
现在我想知道如何显示已经在运行的原始应用程序进程。
这是我在程序类中的代码:
static class Program
{
[STAThread]
static void Main()
{
const string appName = "MyappName";
bool createdNew;
mutex = new Mutex(true, appName, out createdNew);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form form = new Form1();
if (!createdNew)
{
form.Show(); <<=========================== NOT WORKING
form.Visible = true; <<===================== None
form.TopMost = true; <<===================== of
form.BringToFront(); <<===================== these working!
form.WindowState = FormWindowState.Maximized;
return;
}
Application.Run(form);
} private static Mutex mutex = null;
}
Run Code Online (Sandbox Code Playgroud)
我建议您使用一种不同的方法,使用System.Threading.Mutex类和UIAutomation AutomationElement类的组合。
Mutex正如您已经知道的那样,A可以是一个简单的字符串。您可以以 GUID 的形式为应用程序分配互斥锁,但它可以是其他任何形式。
让我们假设这是当前的 Application Mutex:
string ApplicationMutex = "BcFFcd23-3456-6543-Fc44abcd1234";
//Or
string ApplicationMutex = "Global\BcFFcd23-3456-6543-Fc44abcd1234";
Run Code Online (Sandbox Code Playgroud)
注意:
使用"Global\"Prefix 来定义 Mutex 的范围。如果未指定"Local\"前缀,则假定并使用前缀。当多个桌面处于活动状态或终端服务在服务器上运行时,这将阻止进程的单个实例。
如果我们想验证另一个正在运行的进程是否已经注册了相同的Mutex,我们尝试注册我们的Mutex,如果失败,我们的应用程序的另一个实例已经在运行。
我们让用户知道 Application 只支持单个实例,然后切换到运行进程,显示它的界面,最后退出重复的 Application,处理Mutex.
激活应用程序先前实例的方法可能因应用程序类型而异,但只有一些细节会发生变化。
我们可以使用Process..GetProcesses()来检索正在运行的进程列表,并验证其中一个进程是否与我们的进程具有相同的详细信息。
在这里,您有一个窗口化应用程序(它有一个 UI),因此已经可以过滤列表,排除那些没有MainWindowHandle 的进程。
Process[] windowedProcesses =
Process.GetProcesses().Where(p => p.MainWindowHandle != IntPtr.Zero).ToArray();
Run Code Online (Sandbox Code Playgroud)
为了确定正确的,我们可以测试Process.ProcessName是否相同。
但此名称与可执行文件名称相关联。如果文件名更改(有人出于某种原因更改了它),我们将永远不会以这种方式识别进程。
识别正确 Process 的一种可能方法是测试Process.MainModule.FileVersionInfo.ProductName并检查它是否相同。
找到后,可以将原始应用程序放在AutomationElement使用MainWindowHandle已识别进程的创建的前面。
在AutomationElement可以自动不同模式(的,对于UI元素提供自动化功能的控制排序)。
甲WindowPattern允许控制一个窗口基控制(平台是无关紧要的,可以是一个WinForms'窗体或WPF的窗口)。
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
WindowPattern wPattern = element.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
wPattern.SetWindowVisualState(WindowVisualState.Normal);
Run Code Online (Sandbox Code Playgroud)
要使用该
UIAutomation功能,你必须在你的项目中添加这些refereneces:
-UIAutomationClient
-UIAutomationTypes
更新:
由于应用程序的窗体可能被隐藏,Process.GetProcesses()不会找到它的窗口句柄,因此AutomationElement.FromHandle()不能用于识别Form窗口。
在不取消 UIAutomation“模式”的情况下,一种可能的解决方法是使用Automation.AddAutomationEventHandler注册自动化事件,这允许在 UI 自动化事件发生时接收通知,例如即将显示新窗口(程序正在运行)。
仅当应用程序需要作为单一实例运行时才注册该事件。引发事件时,新的进程AutomationElement名称(Windows 标题文本)与当前进程名称进行比较,如果相同,隐藏的表单将取消隐藏并以正常状态显示自己。
作为故障安全措施,我们提供了一个信息MessageBox。该MessageBox标题具有相同的标题作为应用程序MainForm。
(使用WindowsState设置为Minimized且Visible属性设置为的 Form 进行测试false)。
在原始进程被带到前面之后,我们只需要关闭当前线程并释放我们创建的资源(在这种情况下主要是互斥锁)。
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Automation;
using System.Windows.Forms;
static class Program
{
static Mutex mutex = null;
[STAThread]
static void Main()
{
Application.ThreadExit += ThreadOnExit;
string applicationMutex = @"Global\BcFFcd23-3456-6543-Fc44abcd1234";
mutex = new Mutex(true, applicationMutex);
bool singleInstance = mutex.WaitOne(0, false);
if (!singleInstance)
{
string appProductName = Process.GetCurrentProcess().MainModule.FileVersionInfo.ProductName;
Process[] windowedProcesses =
Process.GetProcesses().Where(p => p.MainWindowHandle != IntPtr.Zero).ToArray();
foreach (Process process in windowedProcesses.Where(p => p.MainModule.FileVersionInfo.ProductName == appProductName))
{
if (process.Id != Process.GetCurrentProcess().Id)
{
AutomationElement wElement = AutomationElement.FromHandle(process.MainWindowHandle);
if (wElement.Current.IsOffscreen)
{
WindowPattern wPattern = wElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
#if DEBUG
WindowInteractionState state = wPattern.Current.WindowInteractionState;
Debug.Assert(!(state == WindowInteractionState.NotResponding), "The application is not responding");
Debug.Assert(!(state == WindowInteractionState.BlockedByModalWindow), "Main Window blocked by a Modal Window");
#endif
wPattern.SetWindowVisualState(WindowVisualState.Normal);
break;
}
}
}
Thread.Sleep(200);
MessageBox.Show("Application already running", "MyApplicationName",
MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
}
if (SingleInstance) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyAppMainForm());
}
else {
Application.ExitThread();
}
}
private static void ThreadOnExit(object s, EventArgs e)
{
mutex.Dispose();
Application.ThreadExit -= ThreadOnExit;
Application.Exit();
}
}
Run Code Online (Sandbox Code Playgroud)
在应用程序MainForm构造函数中:(
这用于在运行新实例时隐藏应用程序的主窗口,因此过程中Program.cs找不到其句柄)
public partial class MyAppMainForm : Form
{
public MyAppMainForm()
{
InitializeComponent();
Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent,
AutomationElement.RootElement,
TreeScope.Subtree, (uiElm, evt) =>
{
AutomationElement element = uiElm as AutomationElement;
string windowText = element.Current.Name;
if (element.Current.ProcessId != Process.GetCurrentProcess().Id && windowText == this.Text)
{
this.BeginInvoke(new MethodInvoker(() =>
{
this.WindowState = FormWindowState.Normal;
this.Show();
}));
}
});
}
}
Run Code Online (Sandbox Code Playgroud)