当前位置:网站首页>C # judge whether the application is started and displayed

C # judge whether the application is started and displayed

2022-06-22 02:10:00 coder i++

[STAThread]
private static void Main()
{
    
	Process process  = publicClass.RunningInstance();
	if(process!=null)
	{
    
		publicClass.HandleRunningInstance(process);
	}
	else
	{
    
		Application.EnableVisualStyles();
		Application.SetCompatiableTextRenderingDefault(false);
		Application.Run(new FormName());
	}
}

Show form

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

internal class publicClassa
{
    
    public static void HandleRunningInstance(Process instance)
	{
    
		publicClass.ShowWindowAsync(instance.MainWindowHandle, 1);
		publicClass.SetForegroundWindow(instance.MainWindowHandle);
	}

	public static Process RunningInstance()
	{
    
		Process process;
		Process currentProcess = Process.GetCurrentProcess();
		Process[] processesByName = Process.GetProcessesByName(currentProcess.ProcessName);
		int num = 0;
		while (true)
		{
    
			if (num < (int)processesByName.Length)
			{
    
				Process process1 = processesByName[num];
				if (process1.Id != currentProcess.Id)
				{
    
					if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == currentProcess.MainModule.FileName)
					{
    
						process = process1;
						break;
					}
				}
				num++;
			}
			else
			{
    
				process = null;
				break;
			}
		}
		return process;
	}

	[DllImport("User32.dll", CharSet=CharSet.None, ExactSpelling=false)]
	private static extern bool SetForegroundWindow(IntPtr hWnd);

	[DllImport("User32.dll", CharSet=CharSet.None, ExactSpelling=false)]
	private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
}

原网站

版权声明
本文为[coder i++]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220203549234.html