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

介绍 本文将描述了两件事: 如何检查现有的c# Windows应用程序的实例。如何检查是否一个MDI子将一个MDI父,如果它已经加载,然后激活它,而不是创建一个新的实例并设置它作为一个MDI的孩子。 示例代码是用c#写的。本文将尤其是帮助那些VB 6.0程序员和最近转移到。net。 检查现有的Windows应用程序的实例 隐藏,收缩,复制Code

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
    }
}

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

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的孩子。 假设我有一个Windows表单命名frmModule,我想把它作为一个MDI的MDI子形式。我可以叫ActivateThisChill()的函数形式的名称作为参数,来完成这项工作: 隐藏,收缩,复制Code

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父是否特殊形式的静态属性赋值,然后采取相应的行动。 的兴趣点 我的其他感兴趣的文章: 与Oracle使用水晶报表,参数化查询(水晶报表传递SQL查询参数)将数字证书(公钥)附加到一个HTTPS SSL请求 本文转载于:http://www.diyabc.com/frontweb/news10727.html

posted @ 2020-08-11 01:29  Dincat  阅读(166)  评论(0编辑  收藏  举报