禁用多进程启动
//禁止双进程
bool canCreateNew;
using (System.Threading.Mutex m = new System.Threading.Mutex(true, System.Windows.Forms.Application.ProductName, out canCreateNew))
{
if (!canCreateNew)
{
this.Shutdown();
}
}
删除原有进程
/// <summary>
/// 删除原有进程
/// </summary>
/// <param name="processName"></param>
private void KillProcess(string processName)
{
//得到所有打开的进程
try
{
Process currentProcess = Process.GetCurrentProcess();
var processes = Process.GetProcessesByName(processName).Where(process=> process.Id!=currentProcess.Id);
foreach (Process thisproc in processes)
{
//找到程序进程,kill之。
if (!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch (Exception ex)
{
}
}
设置开机自启动
private void SetAppAutoRun(bool autoRun)
{
if (autoRun) //设置开机自启动
{
string path = System.Windows.Forms.Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
rk2.SetValue("JcShutdown", path);
rk2.Close();
rk.Close();
}
else //取消开机自启动
{
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
rk2.DeleteValue("JcShutdown", false);
rk2.Close();
rk.Close();
}
}
App.cs中完整代码:
public partial class App : Application
{
public App()
{
//禁止双进程
bool canCreateNew;
using (System.Threading.Mutex m = new System.Threading.Mutex(true, System.Windows.Forms.Application.ProductName, out canCreateNew))
{
if (!canCreateNew)
{
this.Shutdown();
}
}
SetAppAutoRun(true);
Startup += App_Startup;
}
private void SetAppAutoRun(bool autoRun)
{
if (autoRun) //设置开机自启动
{
MessageBox.Show("设置开机自启动,需要修改注册表", "提示"); // hovertree.com
string path = System.Windows.Forms.Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
rk2.SetValue("JcShutdown", path);
rk2.Close();
rk.Close();
}
else //取消开机自启动
{
MessageBox.Show("取消开机自启动,需要修改注册表", "提示");
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun");
rk2.DeleteValue("JcShutdown", false);
rk2.Close();
rk.Close();
}
}
private void App_Startup(object sender, StartupEventArgs e)
{
new AutoCleanCacheHelper(CleanCacheVeiwModel.ViewModel).Start();
}
}










