zoukankan      html  css  js  c++  java
  • C#实现只许一个实例运行(使用mutex类)

    在google上搜了很多(全是中文的),找了半天也没有解决问题。

    最后没办法,只能搜索e版的了。于是找到了下面的答案。

    metex是mutual exclusion 的缩写,

    完整的实现参照一下:

    代码
    using System.Runtime.InteropServices;
    namespace TST.SINGLE
    {
    public class TSTPGM
    {
    [DllImport(
    "user32.dll")]
    [
    return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
    bool createdNew = true;
    using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
    {
    if (createdNew)
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(
    false);
    Application.Run(
    new MainForm());
    }
    else
    {
    Process current
    = Process.GetCurrentProcess();
    foreach (Process process in Process.GetProcessesByName(current.ProcessName))
    {
    if (process.Id != current.Id)
    {
    SetForegroundWindow(process.MainWindowHandle);
    break;
    }
    }
    }
    }
    }
    }
    }
  • 相关阅读:
    手机适配与viewport
    Vue组件之间的传值
    作用域链、闭包以及this的使用
    浏览器兼容性
    闭包
    BFC自适应布局
    Mybatis 事务管理
    Mybatis数据源
    Mybatis 缓存分析
    设计模式之禅(2)-设计模式
  • 原文地址:https://www.cnblogs.com/leelike/p/1839651.html
Copyright © 2011-2022 走看看