WinForm只能运行一个实例,存在则激活

2021年11月26日 阅读数:14
这篇文章主要向大家介绍WinForm只能运行一个实例,存在则激活,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

思路

经过Process类获取当前运行的实例,存在时经过User32.dll接口激活窗口。code

MainHelper

public class MainHelper
{
    public static Process RunningInstance(string location)
    {
        var current = Process.GetCurrentProcess();
        var processes = Process.GetProcessesByName(current.ProcessName);
        foreach (Process process in processes)
        {
            if (process.Id != current.Id)
            {
                if (location.Replace("/", @"\") == current.MainModule.FileName)
                {
                    return process;
                }
            }
        }
        return null;
    }

    public static void Active(Process instance)
    {
        ShowWindowAsync(instance.MainWindowHandle, 3);
        SetForegroundWindow(instance.MainWindowHandle);
    }

    [DllImport("User32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

    [DllImport("User32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
}

调用示例

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    var location = Assembly.GetExecutingAssembly().Location;
    var instance = MainHelper.RunningInstance(location);
    if (instance != null)
    {
        MainHelper.Active(instance);
    }
    else
    {
        Application.Run(new Form1());
    }
}