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;
- namespace Core {
- /// <summary>
- /// Ensures that only process is executed at a time
- /// </summary>
- internal class SingleInstanceHelper:IDisposable {
- [DllImport("user32.dll",EntryPoint = "SetForegroundWindow")]
- static extern bool SetForegroundWindow(IntPtr hWnd);
- readonly bool _onlyInstance;
- readonly Process _firstProcess;
- public Process FirstProcess {
- get { return _firstProcess; }
- }
- public bool OnlyInstance {
- get {
- return _onlyInstance;
- }
- }
- public SingleInstanceHelper() {
- _firstProcess = PriorProcess();
- _onlyInstance = _firstProcess == null;
- }
- public bool ShowFirstInstance() {
- if(_firstProcess == null)
- return false;
- if(_firstProcess.MainWindowHandle == IntPtr.Zero)
- return false;
- SetForegroundWindow(_firstProcess.MainWindowHandle);
- return true;
- }
- /// <summary>
- /// Returns a System.Diagnostics.Process pointing to
- /// a pre-existing process with the same name as the
- /// current one, if any; or null if the current process is unique.
- /// </summary>
- /// <returns>Existing Process if any, otherwise null if no previous processes are found</returns>
- Process PriorProcess() {
- using(Process curr = Process.GetCurrentProcess()) {
- Process[] procs = Process.GetProcessesByName(curr.ProcessName);
- Process[] exceptPrior = null;
- try {
- foreach(Process p in procs) {
- if((p.Id != curr.Id) &&
- (p.MainModule.FileName == curr.MainModule.FileName)) {
- exceptPrior = procs.Except(new Process[] { p }).ToArray();
- return p;
- }
- }
- exceptPrior = procs;
- }
- finally {
- foreach(var item in exceptPrior)
- item.Dispose();
- }
- return null;
- }
- }
- public void Dispose() {
- if(_firstProcess != null) {
- _firstProcess.Dispose();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment