Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Windows.Forms;
- namespace Core.System.Diagnostics {
- public static class ProcessHelper {
- const int SW_RESTORE = 9;
- [DllImport("user32.dll",EntryPoint = "SetForegroundWindow")]
- public static extern bool SetForegroundWindow(IntPtr hWnd);
- [DllImport("user32.dll")]
- public static extern Boolean ShowWindow(IntPtr hWnd,Int32 nCmdShow);
- /// <summary>
- /// Ensures a process single insance
- /// </summary>
- /// <param name="mainWidowTitle">Main widow title</param>
- /// <returns>True if the same process is already running</returns>
- public static bool EnsureSingleInsance(string mainWidowTitle,bool focusRunningApp = true) {
- Process current = Process.GetCurrentProcess();
- //get active title if no main title
- if(Form.ActiveForm != null)
- mainWidowTitle = Form.ActiveForm.Text;
- //find process
- Process alreadyRunning = Process.GetProcessesByName(current.ProcessName)
- .Where(p => {
- try {
- if(p.MainWindowTitle.StartsWith(mainWidowTitle)) {
- return p.MainModule.FileName == current.MainModule.FileName;
- }
- return false;
- }
- catch {
- return false;
- }
- })
- .FirstOrDefault();
- //show existing process
- if(alreadyRunning != null) {
- if(focusRunningApp) {
- IntPtr handle = alreadyRunning.MainWindowHandle;
- ShowWindow(handle,SW_RESTORE);
- SetForegroundWindow(handle);
- }
- return false;
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment