检查Windows应用程序的现有实例,并设置MDI子程序的MDI父窗体

介绍

本文将描述了两件事:

如何检查现有的c# Windows应用程序的实例。如何检查是否一个MDI子将一个MDI父,如果它已经加载,然后激活它,而不是创建一个新的实例并设置它作为一个MDI的孩子。

示例代码是用c#写的。本文将尤其是帮助那些VB 6.0程序员和最近转移到。net。

检查现有的Windows应用程序的实例

隐藏,收缩,复制Codeusing 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
}

}

注意:而不是上面的方法检查的进程名称,我们也可以使用一个互斥锁,但这种方法很容易比互斥,这需要一个线程的知识。这个方法工作得很好除非你改变进程名称一些具体原因。

交替使用互斥锁

隐藏,复制Codeusing 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的孩子。

假设我有一个Windows表单命名frmModule,我想把它作为一个MDI的MDI子形式。我可以叫ActivateThisChill()的函数形式的名称作为参数,来完成这项工作:

隐藏,收缩,复制Codeif (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父是否特殊形式的静态属性赋值,然后采取相应的行动。

的兴趣点

我的其他感兴趣的文章:

与Oracle使用水晶报表,参数化查询(水晶报表传递SQL查询参数)将数字证书(公钥)附加到一个HTTPS SSL请求

本文转载于:http://www.diyabc.com/frontweb/news10727.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值