Windows Vista.NET 1.0Windows 2003.NET 1.1.NET 3.0Windows 2000Windows XP.NET 2.0.NET 3.5C# 2.0C# 3.0中级开发Windows.NETC#
检查 Windows 应用程序的现有实例,并设置 MDI 子窗体的 MDI 父窗体






2.88/5 (8投票s)
如何在 C# Windows 应用程序中检查 Windows 应用程序的现有实例,以及如何设置 MDI 子窗体的 MDI 父窗体,如何列出所有 MDI 子窗体等。
引言
本文将介绍两件事
- 如何检查 C# Windows 应用程序的现有实例。
- 如何检查 MDI 子窗体是否设置为 MDI 父窗体,如果已经加载,则仅激活它,而不是创建新实例并将其设置为 MDI 子窗体。
示例代码是用 C# 编写的。本文将特别帮助那些从 VB 6.0 程序员转移到 .NET 的人。
检查 Windows 应用程序的现有实例
using System.Diagnostics;
private static bool getPrevInstance()
{
//get the name of current process, i,e the process
//name of this current application
string currPrsName = Process.GetCurrentProcess().ProcessName;
//Get the name of all processes having the
//same name as this process name
Process[] allProcessWithThisName
= Process.GetProcessesByName(currPrsName);
//if more than one process is running return true.
//which means already previous instance of the application
//is running
if (allProcessWithThisName.Length > 1)
{
MessageBox.Show("Already Running");
return true; // Yes Previous Instance Exist
}
else
{
return false; //No Prev Instance Running
}
}
注意:除了上述通过进程名称检查的方法外,我们还可以使用互斥锁,但与互斥锁相比,这种方法更简单,因为互斥锁需要了解线程。除非你出于某些特定原因更改进程名称,否则此方法将运行良好。
使用互斥锁的替代方法
using System.Threading;
bool appNewInstance;
Mutex m = new Mutex(true, "ApplicationName", out appNewInstance);
if (!appNewInstance)
{
// Already Once Instance Running
MessageBox.Show("One Instance Of This App Allowed.");
return;
}
GC.KeepAlive(m);
检查 MDI 子窗体是否设置为 MDI 父窗体
以下代码将检查 MDI 子窗体是否设置为 MDI 父窗体,如果已经加载,则仅激活它,而不是创建新实例并将其设置为 MDI 子窗体。
假设我有一个名为 frmModule
的 Windows 窗体,我想将其设置为 MDI 窗体的 MDI 子窗体。我可以使用窗体的名称作为参数调用函数 ActivateThisChill()
来完成此操作
if (ActivateThisChild("frmModule") == false)
{
frmModule newMDIChild = new frmModule();
newMDIChild.Text = "Module";
newMDIChild.MdiParent = this;
newMDIChild.Show();
}
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipTitle = " Project Tracker Suite (PTS)";
notifyIcon1.BalloonTipText = " PTS: Modules";
notifyIcon1.ShowBalloonTip(2000);
//This function will return true or false.
//false means this form was not previously set
//as mdi child hence needs to creat a instance
//and set it as a mdi child.
private Boolean ActivateThisChild(String formName)
{
int i;
Boolean formSetToMdi = false;
for (i = 0; i < this.MdiChildren.Length; i++)
// loop for all the mdi children
{
if (this.MdiChildren[i].Name == formName)
// find the Mdi child with the same name as your form
{
// if found just activate it
this.MdiChildren[i].Activate();
formSetToMdi = true;
}
}
if (i == 0 || formSetToMdi == false)
// if the given form not found as mdi child return false.
return false;
else
return true;
}
注意:另一种方法是在每个窗体中使用一个静态属性,并在你的 MDI 父窗体中检查该特定窗体的静态属性是否被赋值,然后据此采取行动。
关注点
我感兴趣的其他文章有