Step1:修改Program,可以实现仅允许启动一次程序实例,且不可直接启动
static class Program
{
private static System.Threading.Mutex mutex;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mutex = new System.Threading.Mutex(true, "FTZNFView"); //此为程序进程名,启动时检测是否已有这个进程,如果已有则不启动
if (mutex.WaitOne(0, false))
{
if (args.Length <= 0)
{
DialogResult dr = MessageBox.Show("无法直接启动本程序,请咨询开发人员!");
if (dr == DialogResult.OK)
Application.Exit();
}
if (args.Length == 1)
{
if (args[0] == "吾等烟雨") //这个字符串可以理解为启动秘钥,在程序启动时传入这个秘钥,程序才能启动
{
Application.Run(new FTZNFView(args));
}
else
{
MessageBox.Show("启动参数不正确,请咨询开发人员!");
Application.Exit();
}
}
}
else
{
MessageBox.Show("程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
}
}
Step2
需要调用该程序时,定义一个方法
public bool StartProcess(string filename, string[] args)
{
try
{
string s = "";
foreach (string arg in args)
{
s = s + arg + " ";
}
s = s.Trim();
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(filename, s);
myprocess.StartInfo = startInfo;
//通过以下参数可以控制exe的启动方式,具体参照 myprocess.StartInfo.下面的参数,如以无界面方式启动exe等
myprocess.StartInfo.UseShellExecute = false;
myprocess.Start();
return true;
}
catch (Exception ex)
{
MessageBox.Show("启动应用程序时出错!原因:" + ex.Message);
}
return false;
}
private void btn1_Click(object sender, System.EventArgs e)
{
string[] arg = new string[1];
arg[0] = "吾等烟雨";
StartProcess("FTZNFView",arg);
}