System.Diagnostics.Process.GetProcessById(int)

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

639 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 : HealthMonitor.cs
with MIT License
from 0ffffffffh

public bool Start()
        {
            this.process = Process.GetProcessById(this.pid);

            if (this.process == null)
            {
                Log.Error("Pid: {0} could not be found.", pid);
                return false;
            }

            this.processPath = this.process.MainModule.FileName;
            this.processArgs = this.process.StartInfo.Arguments;
            
            Log.Verbose(this.processArgs);

            this.process.Exited += Process_Exited;
            this.process.EnableRaisingEvents = true;

            switch (this.procType)
            {
                case ProcessType.BackendProcess:
                    BackendHealthMon = this;
                    break;
                case ProcessType.MemcachedProcess:
                    MemcachedHealthMon = this;
                    break;
            }

            Log.Info("Monitoring started on Pid: {0} for the type of {1} process", this.pid, this.procType);
            
            return true;
        }

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

public static MemcachedProcess Attach(int pid)
        {
            MemcachedProcess mcproc;
            Process nativeProcess;

            nativeProcess = Process.GetProcessById(pid);

            if (nativeProcess==null)
            {
                Log.Critical("Pid {0} could not be found", pid);
                return null;
            }

            nativeProcess.Exited += Process_Exited;
            nativeProcess.EnableRaisingEvents = true;

            mcproc = new MemcachedProcess();
            mcproc.process = nativeProcess;

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            Log.Info("Pid {0} attached successfuly as memcachedprocess", pid);

            return mcproc;
        }

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 : Job.cs
with GNU General Public License v3.0
from 2dust

public bool AddProcess(int processId)
        {
            return AddProcess(Process.GetProcessById(processId).Handle);
        }

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

public void V2rayStopPid(int pid)
        {
            try
            {
                Process _p = Process.GetProcessById(pid);
                KillProcess(_p);
            }
            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 : ProcessExtensionL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task SuccessReadProcessEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                string envName = Guid.NewGuid().ToString();
                string envValue = Guid.NewGuid().ToString();

                Process sleep = null;
                try
                {
#if OS_WINDOWS
                    string node = Path.Combine(TestUtil.GetSrcPath(), @"..\_layout\externals\node12\bin\node");
#else
                    string node = Path.Combine(TestUtil.GetSrcPath(), @"../_layout/externals/node12/bin/node");
                    hc.EnqueueInstance<IProcessInvoker>(new ProcessInvokerWrapper());
#endif
                    var startInfo = new ProcessStartInfo(node, "-e \"setTimeout(function(){{}}, 15 * 1000);\"");
                    startInfo.Environment[envName] = envValue;
                    sleep = Process.Start(startInfo);

                    var timeout = Process.GetProcessById(sleep.Id);
                    while (timeout == null)
                    {
                        await Task.Delay(500);
                        timeout = Process.GetProcessById(sleep.Id);
                    }

                    try
                    {
                        trace.Info($"Read env from {timeout.Id}");
                        var value = timeout.GetEnvironmentVariable(hc, envName);
                        if (string.Equals(value, envValue, StringComparison.OrdinalIgnoreCase))
                        {
                            trace.Info($"Find the env.");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        trace.Error(ex);
                    }

                    replacedert.True(false, "Fail to retrive process environment variable.");
                }
                finally
                {
                    sleep?.Kill();
                }
            }
        }

19 Source : VolumeSMTC.cs
with MIT License
from ADeltaX

public static bool FindSMTCAndHide()
        {
            IntPtr hWndHost = IntPtr.Zero;

            while ((hWndHost = FindWindowEx(IntPtr.Zero, hWndHost, "NativeHWNDHost", "")) != IntPtr.Zero)
            {
                IntPtr hWndDUI;
                if ((hWndDUI = FindWindowEx(hWndHost, IntPtr.Zero, "DirectUIHWND", "")) != IntPtr.Zero)
                {
                    GetWindowThreadProcessId(hWndHost, out int pid);
                    if (Process.GetProcessById(pid).ProcessName.ToLower() == "explorer")
                    {
                        ShowWindowAsync(hWndDUI, 6);
                        ShowWindowAsync(hWndHost, 11);
                        ShowWindowAsync(hWndDUI, 11);

                        unchecked
                        {
                            int extendedStyle = GetWindowLong(hWndDUI, GWL_STYLE);
                            SetWindowLongPtr(hWndDUI, GWL_STYLE, extendedStyle | (int)WindowInBandWrapper.WindowStyles.WS_POPUP | (int)WindowInBandWrapper.WindowStyles.WS_CLIPCHILDREN);

                            int extendedStyle2 = GetWindowLong(hWndHost, GWL_STYLE);
                            SetWindowLongPtr(hWndHost, GWL_STYLE, extendedStyle2 | (int)WindowInBandWrapper.WindowStyles.WS_POPUP | (int)WindowInBandWrapper.WindowStyles.WS_CLIPCHILDREN);
                        }

                        SetWindowPos(hWndHost, IntPtr.Zero, 0, 0,
                                0,
                                0, 0x0010);

                        SetWindowPos(hWndDUI, IntPtr.Zero, 0, 0,
                                0,
                                0, 0x0010);

                        return true;
                    }
                }
            }

            return false;
        }

19 Source : VolumeSMTC.cs
with MIT License
from ADeltaX

public static void FindSMTCAndShow()
        {
            IntPtr hWndHost = IntPtr.Zero;

            while ((hWndHost = FindWindowEx(IntPtr.Zero, hWndHost, "NativeHWNDHost", "")) != IntPtr.Zero)
            {
                IntPtr hWndDUI;
                if ((hWndDUI = FindWindowEx(hWndHost, IntPtr.Zero, "DirectUIHWND", "")) != IntPtr.Zero)
                {
                    GetWindowThreadProcessId(hWndHost, out int pid);
                    if (Process.GetProcessById(pid).ProcessName.ToLower() == "explorer")
                    {
                        //TODO

                        ShowWindowAsync(hWndHost, 9);
                        ShowWindowAsync(hWndDUI, 9);

                        break;
                    }
                }
            }
        }

19 Source : UpdateManager.cs
with MIT License
from admaiorastudio

private void KillRunningProcesses()
        {
            if (File.Exists(_processDatFilePath))
            {
                using (var s = File.OpenText(_processDatFilePath))
                {
                    int processId = 0;

                    try
                    {
                        while(!s.EndOfStream)
                        {
                            processId = Int32.Parse(s.ReadLine());
                            if (processId == 0)
                                continue;

                            var process = Process.GetProcessById(processId);
                            if (process != null && !process.HasExited)
                                process.Kill();
                        }
                    }
                    catch (Exception ex)
                    {                       
                        if (processId != 0)
                            System.Diagnostics.Debug.WriteLine($"RealXaml was unable to kill process with id {processId}");

                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
            }
        }

19 Source : ManualMap.cs
with Apache License 2.0
from aequabit

private static IntPtr GetRemoteModuleHandle(string module, int processId)
        {
            IntPtr zero = IntPtr.Zero;
            Process processById = Process.GetProcessById(processId);
            for (int i = 0; (i < processById.Modules.Count) && zero.IsNull(); i++)
            {
                if (processById.Modules[i].ModuleName.ToLower() == module.ToLower())
                {
                    zero = processById.Modules[i].BaseAddress;
                }
            }
            return zero;
        }

19 Source : ThreadHijack.cs
with Apache License 2.0
from aequabit

public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
        {
            Exception exception;
            this.ClearErrors();
            try
            {
                if (hProcess.IsNull() || hProcess.Compare(-1L))
                {
                    throw new ArgumentException("Invalid process handle.", "hProcess");
                }
                int processId = WinAPI.GetProcessId(hProcess);
                if (processId == 0)
                {
                    throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
                }
                Process processById = Process.GetProcessById(processId);
                if (processById.Threads.Count == 0)
                {
                    throw new Exception("Target process has no targetable threads to hijack.");
                }
                ProcessThread thread = SelectOptimalThread(processById);
                IntPtr ptr = WinAPI.OpenThread(0x1a, false, thread.Id);
                if (ptr.IsNull() || ptr.Compare(-1L))
                {
                    throw new Exception("Unable to obtain a handle for the remote thread.");
                }
                IntPtr zero = IntPtr.Zero;
                IntPtr lpAddress = IntPtr.Zero;
                IntPtr ptr4 = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 1);
                IntPtr[] ptrArray = null;
                if (!ptr4.IsNull())
                {
                    if (WinAPI.SuspendThread(ptr) == uint.MaxValue)
                    {
                        throw new Exception("Unable to suspend the remote thread");
                    }
                    try
                    {
                        uint lpNumberOfBytesRead = 0;
                        WinAPI.CONTEXT pContext = new WinAPI.CONTEXT {
                            ContextFlags = 0x10001
                        };
                        if (!WinAPI.GetThreadContext(ptr, ref pContext))
                        {
                            throw new InvalidOperationException("Cannot get the remote thread's context");
                        }
                        byte[] array = REDIRECT_STUB;
                        IntPtr ptr5 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) array.Length, 0x3000, 0x40);
                        if (ptr5.IsNull())
                        {
                            throw new InvalidOperationException("Unable to allocate memory in the remote process.");
                        }
                        BitConverter.GetBytes(ptr4.Subtract(ptr5.Add(((long) 7L))).ToInt32()).CopyTo(array, 3);
                        BitConverter.GetBytes((uint) (pContext.Eip - ((uint) ptr5.Add(((long) array.Length)).ToInt32()))).CopyTo(array, (int) (array.Length - 4));
                        if (!(WinAPI.WriteProcessMemory(hProcess, ptr5, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length)))
                        {
                            throw new InvalidOperationException("Unable to write stub to the remote process.");
                        }
                        pContext.Eip = (uint) ptr5.ToInt32();
                        WinAPI.SetThreadContext(ptr, ref pContext);
                    }
                    catch (Exception exception1)
                    {
                        exception = exception1;
                        this.SetLastError(exception);
                        ptrArray = null;
                        WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                        WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
                        WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
                    }
                    WinAPI.ResumeThread(ptr);
                    if (this.GetLastError() == null)
                    {
                        Thread.Sleep(100);
                        ptrArray = new IntPtr[dllPaths.Length];
                        byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) dllPaths.Length) << 2);
                        if (buffer2 != null)
                        {
                            for (int i = 0; i < ptrArray.Length; i++)
                            {
                                ptrArray[i] = Win32Ptr.Create((long) BitConverter.ToInt32(buffer2, i << 2));
                            }
                        }
                    }
                    WinAPI.CloseHandle(ptr);
                }
                return ptrArray;
            }
            catch (Exception exception2)
            {
                exception = exception2;
                this.SetLastError(exception);
                return null;
            }
        }

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

public static string GetControlText(IntPtr hWnd)
		{
			Debug.replacedert(hWnd != IntPtr.Zero);
			string processName = null;
			try
			{
				int pid;
				User32.GetWindowThreadProcessId(hWnd, out pid);
				if (pid > 0)
				{
					var p = Process.GetProcessById(pid);
					if (p != null)
						processName = p.ProcessName;
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }

			string txt = null;
			switch (processName)
			{
				case "iexplore":
					txt = GetHtmlControlText(hWnd);
					break;
				default:
					txt = GetWindowControlText(hWnd);
					break;
			}
			return txt;
		}

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

public static string GetWindowUrl(IntPtr hWnd)
		{
			Debug.replacedert(hWnd != IntPtr.Zero);
			string processName = null;
			try
			{
				int pid;
				User32.GetWindowThreadProcessId(hWnd, out pid);
				if (pid > 0)
				{
					var p = Process.GetProcessById(pid);
					if (p != null)
						processName = p.ProcessName.ToLower();
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }

			string url = null;
			switch (processName.ToLower())
			{
				case "chrome":
					url = GetChromeUrl(hWnd);
					break;
				case "opera":
					GetOperaUrl(hWnd);
					break;
				case "firefox":
					GetFirfoxUrl(hWnd);
					break;
				case "iexplore":
				case "explorer":
					url = GetIExploreUrl(hWnd);
					break;
				case "360se":
					url = Get360SeUrl(hWnd);
					break;
				case "maxthon":
					url = GetMaxthonUrl(hWnd);
					break;
				case "baidubrowser":
					url = GetBaiduUrl(hWnd);
					break;
				case "sogouexplorer":
					url = GetSogouUrl(hWnd);
					break;
				case "miniie":
					url = GetMiniIEUrl(hWnd);
					break;
				case "theworld":	// 世界之窗浏览器
					break;
				default:
					url = GetIExploreUrl(hWnd);		// try
					break;
			}
			return url;
		}

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

private static Process GetWindowProcess(IntPtr hWnd)
		{
			Process p = null;
			try
			{
				int pid;
				user32.GetWindowThreadProcessId(hWnd, out pid);
				if (pid > 0)
					p = Process.GetProcessById(pid);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			return p;
		}

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

private string GetConnectedUser(int processPort, AddressFamily addressFamily)
		{
			int pid = 0;
			int dwProcessPort = BitConverter.ToUInt16(new byte[] { BitConverter.GetBytes(processPort)[1], BitConverter.GetBytes(processPort)[0] }, 0);
			if (addressFamily == AddressFamily.InterNetwork)
			{
				foreach (var conn in EnumTcpConnectionsV4())
				{
					if (conn.dwLocalPort == dwProcessPort)
					{
						pid = conn.dwOwningPid;
						break;
					}
				}
			}
			else if (addressFamily == AddressFamily.InterNetworkV6)
			{
				foreach (var conn in EnumTcpConnectionsV6())
				{
					if (conn.dwLocalPort == dwProcessPort)
					{
						pid = conn.dwOwningPid;
						break;
					}
				}
			}
			if (pid > 0)
			{
				using (Process proc = Process.GetProcessById(pid))
				{
					if (proc != null)
					{
						string user = GetDomainUserBySessionId(proc.SessionId);
						proc.Dispose();
						return DomainUser.Create(user).ToString();
					}
				}
			}
			return null;
		}

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

private bool IsPermitedProcess(IPEndPoint remote)
		{
			Debug.replacedert(IPAddress.IsLoopback(remote.Address));
			if (string.IsNullOrEmpty(PermitProcess))
				return true;

			int pid = TcpEngine.GetConnectedProcess(remote);
			if (pid > 0)
			{
				string name = Process.GetProcessById(pid).ProcessName;
				return string.Equals(name, PermitProcess, StringComparison.OrdinalIgnoreCase);
			}
			else
				return false;
		}

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

public static string GetProcessOwner(int processId)
		{
			Debug.replacedert(processId > 0);
			using (Process process = Process.GetProcessById(processId))
			{
				if (process != null)
					return GetSessionUser(process.SessionId);
				else
					return null;
			}
		}

19 Source : Injector.cs
with MIT License
from Akaion

private static Process GetProcess(int processId)
        {
            try
            {
                return Process.GetProcessById(processId);
            }

            catch (ArgumentException)
            {
                throw new ArgumentException($"No process with the ID {processId} is currently running");
            }
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

private SafeProcessHandle OpenProcessHandle(int processId)
        {
            try
            {
                return Process.GetProcessById(processId).SafeHandle;
            }

            catch (ArgumentException)
            {
                throw new ArgumentException($"No process with the id {processId} is currently running");
            }
        }

19 Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void TasksListStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button buttonStop = sender as Button;
                int processID = ((TaskListTask)buttonStop.DataContext).TaskID;
                Process.GetProcessById(processID).Kill();
                AddTextToEventsList("Process has been cancelled by user!", false);
                RemoveTaskFromTasksList(processID, false);
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                AddTextToEventsList("Process cancelled failed: " + ex.Message, false);
            }
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

public static string GetProcessName(IntPtr hwnd)
        {
            int processId = 0;
            try
            {
                GetWindowThreadProcessId(hwnd, out processId);
                var process = Process.GetProcessById(processId);
                return process.MainModule.FileName;
            }
            catch
            {
                try
                {
                    return GetProcessName(processId);
                }
                catch
                {
                    return string.Empty;
                }
            }
        }

19 Source : ProcessExtensions.cs
with MIT License
from AlexanderPro

public static Process GetParentProcess(this Process process)
        {
            var pbi = new PROCESS_BASIC_INFORMATION();
            int returnLength;
            var status = NtQueryInformationProcess(process.GetHandle(), 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
            if (status != 0)
            {
                return null;
            }

            try
            {
                return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
            }
            catch
            {
                return null;
            }
        }

19 Source : MainForm.cs
with MIT License
from AlexanderPro

public bool PreFilterMessage(ref Message m)
        {
            switch (m.Msg)
            {
                case NativeConstants.WM_LBUTTONUP:
                    {
                        if (_isButtonTargetMouseDown)
                        {
                            _isButtonTargetMouseDown = false;
                            NativeMethods.SetCursor(Cursors.Default.Handle);
                            if (!TopMost)
                            {
                                BringToFront();
                            }
                        }
                    }
                    break;

                case NativeConstants.WM_MOUSEMOVE:
                    {
                        try
                        {
                            if (_isButtonTargetMouseDown)
                            {
                                NativeMethods.SetCursor(Properties.Resources.Target32.Handle);
                                var cursorPosition = System.Windows.Forms.Cursor.Position;
                                var element = AutomationElement.FromPoint(new System.Windows.Point(cursorPosition.X, cursorPosition.Y));
                                if (element != null && element.Current.ProcessId != _processId)
                                {
                                    _windowHandle = new IntPtr(element.Current.NativeWindowHandle);
                                    _windowHandle = _windowHandle == IntPtr.Zero ? NativeMethods.WindowFromPoint(new Point(cursorPosition.X, cursorPosition.Y)) : _windowHandle;
                                    if (element.Current.IsPreplacedword)
                                    {
                                        var process = Process.GetProcessById(element.Current.ProcessId);
                                        if (process.ProcessName.ToLower() == "iexplore")
                                        {
                                            if (_windowHandle != IntPtr.Zero)
                                            {
                                                var preplacedwords = WindowUtils.GetPreplacedwordsFromHtmlPage(_windowHandle);
                                                if (preplacedwords.Any())
                                                {
                                                    txtContent.Text = preplacedwords.Count > 1 ? string.Join(Environment.NewLine, preplacedwords.Select((x, i) => "Preplacedword " + (i + 1) + ": " + x)) : preplacedwords[0];
                                                    txtContent.ScrollTextToEnd();
                                                    OnContentChanged();
                                                }
                                            }
                                        } else if (Environment.Is64BitOperatingSystem && !process.HasExited && !process.IsWow64Process())
                                        {
                                            Process.Start(new ProcessStartInfo
                                            {
                                                FileName = _64BitFilePath,
                                                Arguments = string.Format("{0} {1} {2}", Handle.ToInt32(), element.Current.NativeWindowHandle, _messageId)
                                            });
                                        }
                                        else
                                        {
                                            NativeMethods.SetHook(Handle, _windowHandle, _messageId);
                                            NativeMethods.QueryPreplacedwordEdit();
                                            NativeMethods.UnsetHook(Handle, _windowHandle);
                                        }
                                    }
                                    else
                                    {
                                        var text = element.GetTextFromConsole() ?? element.GetTextFromWindow();
                                        txtContent.Text = text == null ? "" : text.TrimEnd().TrimEnd(Environment.NewLine);
                                        txtContent.ScrollTextToEnd();
                                        if (pbContent.Image != null)
                                        {
                                            pbContent.Image.Dispose();
                                            pbContent.Image = null;
                                        }
                                        pbContent.Image = WindowUtils.PrintWindow(_windowHandle);
                                        var windowInformation = WindowUtils.GetWindowInformation(_windowHandle);
                                        FillInformation(windowInformation);
                                        OnContentChanged();
                                    }

                                    btnShowHide.Text = NativeMethods.IsWindowVisible(_windowHandle) ? "Hide" : "Show";
                                    btnShowHide.Visible = true;
                                }
                                else
                                {
                                    btnShowHide.Visible = false;
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    break;
            }

            return false;
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static Process GetProcessByIdSafely(int processId)
        {
            try
            {
                return Process.GetProcessById(processId);
            }
            catch
            {
                return null;
            }
        }

19 Source : ProcessExtensions.cs
with MIT License
from AlexanderPro

public static Process GetParentProcess(this Process process)
        {
            var pbi = new PROCESS_BASIC_INFORMATION();
            int returnLength;
            var status = NativeMethods.NtQueryInformationProcess(process.Handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
            if (status != 0)
            {
                return null;
            }

            try
            {
                return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
            }
            catch
            {
                return null;
            }
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

private static Process GetProcessByIdSafely(int pId)
        {
            try
            {
                return Process.GetProcessById(pId);
            }
            catch
            {
                return null;
            }
        }

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

public static string GetInstanceNameForProcessId(int processId)
        {
            var process = Process.GetProcessById(processId);
            string processName = Path.GetFileNameWithoutExtension(process.ProcessName);

            PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
            string[] instances = cat.GetInstanceNames()
                .Where(inst => inst.StartsWith(processName))
                .ToArray();

            foreach (string instance in instances)
            {
                using (PerformanceCounter cnt = new PerformanceCounter("Process",
                    "ID Process", instance, true))
                {
                    int val = (int)cnt.RawValue;
                    if (val == processId)
                    {
                        return instance;
                    }
                }
            }
            return null;
        }

19 Source : Kill.cs
with MIT License
from Alkl58

public static void Kill_PID()
        {
            List<int> temp_pids = Global.Launched_PIDs;

            // Nuke all PIDs
            foreach (int pid in temp_pids.ToList())
            {
                try
                {
                    List<int> children = Suspend.GetChildProcesses(pid);

                    Process proc_to_kill = Process.GetProcessById(pid);
                    proc_to_kill.Kill();

                    if (children != null)
                    {
                        foreach (int pid_children in children)
                        {
                            Process child_proc_to_kill = Process.GetProcessById(pid_children);
                            child_proc_to_kill.Kill();
                        }
                    }
                }
                catch { }
            }
        }

19 Source : Resume.cs
with MIT License
from Alkl58

public static void ResumeProcess(int pid)
        {
            var process = Process.GetProcessById(pid);

            if (process.ProcessName == string.Empty)
                return;

            foreach (ProcessThread pT in process.Threads)
            {
                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);

                if (pOpenThread == IntPtr.Zero)
                {
                    continue;
                }

                var suspendCount = 0;
                do
                {
                    suspendCount = ResumeThread(pOpenThread);
                } while (suspendCount > 0);

                CloseHandle(pOpenThread);
            }
        }

19 Source : Suspend.cs
with MIT License
from Alkl58

public static void SuspendProcess(int pid)
        {
            var process = Process.GetProcessById(pid); // throws exception if process does not exist

            foreach (ProcessThread pT in process.Threads)
            {
                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);

                if (pOpenThread == IntPtr.Zero)
                {
                    continue;
                }

                SuspendThread(pOpenThread);

                CloseHandle(pOpenThread);
            }
        }

19 Source : NativeMethods.cs
with GNU Lesser General Public License v3.0
from Alois-xx

public static bool ProcessExists(int pid)
        {
            try
            {
                var p = Process.GetProcessById(pid);
                return true;
            }
            catch (ArgumentException)
            {
                return false;
            }
        }

19 Source : NativeMethods.cs
with GNU Lesser General Public License v3.0
from Alois-xx

public static bool IsWin64(int pid)
        {
            return IsWin64(Process.GetProcessById(pid));
        }

19 Source : TargetInformation.cs
with GNU Lesser General Public License v3.0
from Alois-xx

public static string GetProcessName(int pid)
        {
            return Process.GetProcessById(pid).ProcessName;
        }

19 Source : OverlayBase`1.cs
with GNU General Public License v2.0
from AmanoTooko

protected virtual void InitializeTimer()
    {
      this.timer = new System.Timers.Timer();
      this.timer.Interval = 1000.0;
      this.timer.Elapsed += (ElapsedEventHandler) ((o, e) =>
      {
        try
        {
          this.Update();
        }
        catch (Exception ex)
        {
          this.Log(LogLevel.Error, "更新: {0}", (object) ex.ToString());
        }
      });
      this.xivWindowTimer = new System.Timers.Timer();
      this.xivWindowTimer.Interval = 1000.0;
      this.xivWindowTimer.Elapsed += (ElapsedEventHandler) ((o, e) =>
      {
        try
        {
          if (!this.Config.IsVisible || !this.PluginConfig.HideOverlaysWhenNotActive)
            return;
          IntPtr foregroundWindow = NativeMethods.GetForegroundWindow();
          if (foregroundWindow == IntPtr.Zero)
            return;
          uint lpdwProcessId;
          int windowThreadProcessId = (int) NativeMethods.GetWindowThreadProcessId(foregroundWindow, out lpdwProcessId);
          string fileName = Process.GetProcessById((int) lpdwProcessId).MainModule.FileName;
          if (Path.GetFileName(fileName.ToString()) == "ffxiv.exe" || Path.GetFileName(fileName.ToString()) == "ffxiv_dx11.exe" || fileName.ToString() == Process.GetCurrentProcess().MainModule.FileName)
            this.Overlay.Visible = true;
          else
            this.Overlay.Visible = false;
        }
        catch (Exception ex)
        {
          this.Log(LogLevel.Error, "最终幻想14窗口监视: {0}", (object) ex.ToString());
        }
      });
    }

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

private void button2_Click(object sender, EventArgs e)
        {
            this.kc.Init(Process.GetProcessById(Convert.ToInt32(this.comboBox1.SelectedItem?.ToString())).MainWindowHandle);
            System.Threading.Timer timer1 = new System.Threading.Timer((TimerCallback)(x => this.kc.BackgroundKeyPress(Keys.Space)), new object(), 100, 0);
            System.Threading.Timer timer2 = new System.Threading.Timer((TimerCallback)(x => this.kc.BackgroundKeyRelease(Keys.Space)), new object(), 200, 0);
        }

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

private void Panel2_Click(object sender, EventArgs e)
        {
            PidSelect pidSelect = new PidSelect();
            pidSelect.GetPid += (PidSelect.PidSelector)(x =>
            {
                this.kc.isBackGroundKey = true;
                this.kc.InitBackGroundKey(Process.GetProcessById(x).MainWindowHandle);
            });
            pidSelect.ShowDialog();
        }

19 Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

19 Source : ProfilingTargetAdapter.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool CanStartProfiling(ConfigurationSettings settings, int processId)
        {
            using (Process process = Process.GetProcessById(processId))
            {
                ProfilingTargetSettings profilingTargetSettings = new ProfilingTargetSettings(settings.ProfilingTargetSettings);
                bool targetService = _services.IsServiceHostProcess(process, profilingTargetSettings.ServiceName);
                return targetService;
            }
        }

19 Source : Advapi32.cs
with GNU General Public License v3.0
from AndreiFedarets

public static Process GetServiceProcessId(ServiceController sc)
        {
            IntPtr statusProcessPtr = IntPtr.Zero;
            try
            {
                UInt32 dwBytesNeeded;
                // Call once to figure the size of the output buffer.
                QueryServiceStatusEx(sc.ServiceHandle, SC_STATUS_PROCESS_INFO, statusProcessPtr, 0, out dwBytesNeeded);
                if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
                {
                    // Allocate required buffer and call again.
                    statusProcessPtr = Marshal.AllocHGlobal((int) dwBytesNeeded);

                    if (QueryServiceStatusEx(sc.ServiceHandle, SC_STATUS_PROCESS_INFO, statusProcessPtr, dwBytesNeeded, out dwBytesNeeded))
                    {
                        SERVICE_STATUS_PROCESS serviceStatus = new SERVICE_STATUS_PROCESS();
                        Marshal.PtrToStructure(statusProcessPtr, serviceStatus);
                        int processId = (int)serviceStatus.dwProcessId;
                        return Process.GetProcessById(processId);
                    }
                }
            }
            finally
            {
                if (statusProcessPtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(statusProcessPtr);
                }
            }
            return null;
        }

19 Source : Launcher.cs
with GNU General Public License v3.0
from AndreiFedarets

public static Process LaunchInSpecialSession(int sessionId, string fileName, string args, string workingDirectory, StringDictionary environmentVariables)
        {
            Process process;
            IntPtr userToken = IntPtr.Zero;
            IntPtr originalEnvironment = IntPtr.Zero;
            IntPtr customEnvironment = IntPtr.Zero;
            try
            {
                if (!NativeMethods.WTSQueryUserToken(sessionId, ref userToken))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }
                if (!NativeMethods.CreateEnvironmentBlock(ref originalEnvironment, userToken, false))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }
                UInt32 creationFlags = 0;
                if (originalEnvironment != IntPtr.Zero)
                {
                    creationFlags |= 0x400;
                }
                StringDictionary originalEnvironmentVariables = NativeMethods.ReadEnvironmentVariables(originalEnvironment);
                // Append custom environment variables to list.
                foreach (DictionaryEntry variable in environmentVariables)
                {
                    originalEnvironmentVariables.Add(variable.Key.ToString(), variable.Value.ToString());
                }
                StringBuilder newEnvironmentBlock = new StringBuilder();
                foreach (DictionaryEntry variable in originalEnvironmentVariables)
                {
                    newEnvironmentBlock.AppendFormat("{0}={1}\0", variable.Key, variable.Value);
                }
                newEnvironmentBlock.Append("\0");

                customEnvironment = Marshal.StringToHGlobalUni(newEnvironmentBlock.ToString());

                NativeMethods.StartupInfo startupInfo = new NativeMethods.StartupInfo();
                startupInfo.Size = Marshal.SizeOf(startupInfo);


                NativeMethods.ProcessInformation processInformation;
                if (Advapi32.CreateProcessAsUser(userToken, fileName, args, IntPtr.Zero, IntPtr.Zero, false, creationFlags, 
                    customEnvironment, workingDirectory, ref startupInfo, out processInformation))
                {
                    process = Process.GetProcessById((int) processInformation.ProcessId);
                    Kernel32.CloseHandle(processInformation.Process);
                    Kernel32.CloseHandle(processInformation.Thread);
                }
                else
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }
            }
            finally
            {
                if (userToken != IntPtr.Zero)
                {
                    Kernel32.CloseHandle(userToken);
                }
                if (originalEnvironment != IntPtr.Zero)
                {
                    NativeMethods.DestroyEnvironmentBlock(originalEnvironment);
                }
                if (customEnvironment != IntPtr.Zero)
                {
                    NativeMethods.DestroyEnvironmentBlock(customEnvironment);
                }
            }
            return process;
        }

19 Source : ProfilingTargetAdapter.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool CanStartProfiling(ConfigurationSettings settings, int processId)
        {
            using (Process process = Process.GetProcessById(processId))
            {
                ProfilingTargetSettings profilingTargetSettings = new ProfilingTargetSettings(settings.ProfilingTargetSettings);
                string targetProcessName = Path.GetFileNameWithoutExtension(profilingTargetSettings.FileFullName);
                if (!string.Equals(process.ProcessName, targetProcessName, StringComparison.InvariantCultureIgnoreCase))
                {
                    return false;
                }
            }
            return true;
        }

19 Source : ProfilingTargetController.cs
with GNU General Public License v3.0
from AndreiFedarets

internal void AttachProcess(ConfigurationSettings configurationSettings, SessionSettings sessionSettings, int processId)
        {
            Process process = Process.GetProcessById(processId);
            lock (_processes)
            {
                process.EnableRaisingEvents = true;
                process.Exited += OnProcessExited;
                _processes.Add(process);   
            }
        }

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

static void Main(string[] args) {

            if (args.Length != 3) { Environment.Exit(3); return; }

            String msi = args[0];
            String location = args[1];
            Int32 pid = Int32.Parse(args[2]);

            if (pid == 0) { Environment.Exit(100); return; }
            if (!File.Exists(msi)) { Environment.Exit(404); return; }

            Process apptray = Process.GetProcessById(pid);
            String appNameFilename = apptray.MainModule.FileName;
            Boolean apptrayAsExited = apptray.WaitForExit(60000);

            if (!apptrayAsExited) { Environment.Exit(500); return; }

            ProcessStartInfo installerInfo = new ProcessStartInfo() {
                Arguments = $"/i {msi}",
                UseShellExecute = true,
                FileName = "msiexec",
                Verb = "runas"
            };

            Boolean installerAsExited = false;
            try {
                Process installer = Process.Start(installerInfo);
                installerAsExited = installer.WaitForExit(60000);
            } catch (Win32Exception ex) {
                if (ex.NativeErrorCode == 1223) { Environment.Exit(1223); return; }
            }

            if (installerAsExited && File.Exists(appNameFilename)) {
                Process.Start(new ProcessStartInfo() {
                    Arguments = $"/C del /Q /F {msi}",
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "cmd",
                });
                Process.Start(appNameFilename);
            }

        }

19 Source : ChatOverlaysController.cs
with MIT License
from anoyetta

private static void RefreshFFXIVIsActive()
        {
            try
            {
                // フォアグラウンドWindowのハンドルを取得する
                var hWnd = NativeMethods.GetForegroundWindow();

                // プロセスIDに変換する
                NativeMethods.GetWindowThreadProcessId(hWnd, out uint pid);

                if (pid == SharlayanController.Instance.HandledProcessID)
                {
                    IsFFXIVActive = true;
                    IsFFXIVRunning = true;
                    ffxivShutdownTimestamp = DateTime.MaxValue;
                    return;
                }

                // フォアウィンドウのファイル名を取得する
                var p = Process.GetProcessById((int)pid);
                if (p != null)
                {
                    var fileName = Path.GetFileName(
                        p.MainModule.FileName);

                    var currentProcessFileName = Path.GetFileName(
                        Process.GetCurrentProcess().MainModule.FileName);

                    if (fileName.ToLower() == "ffxiv.exe" ||
                        fileName.ToLower() == "ffxiv_dx11.exe" ||
                        fileName.ToLower() == currentProcessFileName.ToLower())
                    {
                        IsFFXIVActive = true;
                        IsFFXIVRunning = true;
                        ffxivShutdownTimestamp = DateTime.MaxValue;
                    }
                    else
                    {
                        p = Process.GetProcesses()
                            .FirstOrDefault(x =>
                                x.ProcessName == "ffxiv" ||
                                x.ProcessName == "ffxiv_dx11");

                        IsFFXIVActive = false;

                        var isRunning = p != null;
                        if (IsFFXIVRunning != isRunning)
                        {
                            IsFFXIVRunning = isRunning;

                            if (!isRunning)
                            {
                                ffxivShutdownTimestamp = DateTime.Now;
                            }
                        }
                    }
                }

                Thread.Sleep(TimeSpan.FromSeconds(7));
            }
            catch (Win32Exception)
            {
            }
        }

19 Source : Notes.cs
with MIT License
from anoyetta

private static void RefreshFFXIVIsActive()
        {
            try
            {
                // フォアグラウンドWindowのハンドルを取得する
                var hWnd = NativeMethods.GetForegroundWindow();

                // プロセスIDに変換する
                NativeMethods.GetWindowThreadProcessId(hWnd, out uint pid);

                // フォアウィンドウのファイル名を取得する
                var p = Process.GetProcessById((int)pid);
                if (p != null)
                {
                    var fileName = Path.GetFileName(
                        p.MainModule.FileName);

                    if (ActiveTarets.Any(x => string.Equals(
                        x,
                        fileName,
                        StringComparison.OrdinalIgnoreCase)))
                    {
                        IsFFXIVActive = true;
                    }
                    else
                    {
                        IsFFXIVActive = false;
                    }
                }
            }
            catch (Win32Exception)
            {
            }
        }

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

public static void MemInfo(string pidString, string memAddrStr)
        {
            int pid;
            uint pageSize = 0x1000;

            // ensure the input is an integer
            try
            {
                pid = Convert.ToInt32(pidString);

            }

            // If not, go back to the menu and alert the usre
            catch (Exception ex)
            {
                Console.WriteLine("Input not an integer.  Please try again");
                help();
                pid = 0;
            }

            // Ensure the pid is to a running process
            try
            {
                Process proc = Process.GetProcessById(pid);
            }
            // If not go to the help an dinform the user
            catch (Exception ex)
            {
                Console.WriteLine("Not a valid process. \nError: {0}", ex);
                help();
            }

            
            // ensure that the user entered a hex address
            try
            {
                Convert.ToInt64(memAddrStr, 16);
            }
            // If not alert the user and go to the help
            catch(Exception ex)
            {
                Console.WriteLine("Invalid Memory address format.  Must be in hex, 0x... format.  Error: {0}", ex);
                help();
            }

            // Create a new pointer from converting the user input string to a 64 bit integer 
            IntPtr base_mem_address = new IntPtr(Convert.ToInt64(memAddrStr, 16));


            try
            {
                // Create a new basic memory information instancefrom the struct created belwo
                MEMORY_BASIC_INFORMATION64 mem_basic_info = new MEMORY_BASIC_INFORMATION64();

                // Winsows APOI function callopening the process with desired access level and saving the handle to the process 
                IntPtr pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, pid);

                // Windows API funciton call to query the process memory information and save the information in the basic information struct instance created above
                VirtualQueryEx(pHandle, base_mem_address, out mem_basic_info, pageSize);

                // Call the get Memory Constant String funciton and save it a s a string
                string memProtectConstStr = getMemProtectConstStr(mem_basic_info.Protect);

                // Write the Memory protection information string to the console 
                Console.WriteLine("\nProtection Information: {0}", memProtectConstStr);
            }
            // Or else go to the help and alert the user of the failure
            catch(Exception ex)
            {
                Console.WriteLine("\nFailed to Open memory location.  \nError: {0}", ex);
                help();
            }
        }

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

public static void MemDump(string pidString, string memAddrStr)
        {

            int buffWidth = 16;
            int pid;
            int offset = 0x1000;
            int bytesRead = 0;

            Int64 baseAddr;
            var byteArray = new byte[offset];

            // Ensure the input pid is an integer
            try
            {
                pid = Convert.ToInt32(pidString);

            }
            // If not go to the help and alert the user
            catch (Exception ex)
            {
                Console.WriteLine("\nInput not an integer.  Please try again");
                help();
                pid = 0;
            }

            // Ensure the pid is to a running process
            try
            {
                Process proc = Process.GetProcessById(pid);
            }
            // If not go to the help an dinform the user
            catch(Exception ex)
            {
                Console.WriteLine("Not a valid process. \nError: {0}", ex);
                help();
            }

            // Ensure the input is a memory address in hex
            try
            {
                Convert.ToInt64(memAddrStr, 16);
            }
            // if not go to the help and alert the user
            catch (Exception ex)
            {
                Console.WriteLine("\nInvalid Memory address format.  Must be in hex, 0x... format.  \nError: {0}", ex);
                help();
            }

            // Create a new pointer from converting the user input string to a 64 bit integer 
            IntPtr base_mem_address = new IntPtr(Convert.ToInt64(memAddrStr, 16));

            

            try
            {
                // Windows API fucntion call opening the process with desired access level and saving the handle to the process 
                IntPtr pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, pid);

                // Windows API call fucntion to read the process memory into a byte array
                ReadProcessMemory(pHandle, base_mem_address, byteArray, offset, ref bytesRead);

            }
            // If it fails, go to help and alert the user
            catch(Exception ex)
            {
                Console.WriteLine("Unable to dump memory.  \nError: {0}", ex);
                help();
            }

            int position = 0;
            int padding = (buffWidth * 2) + buffWidth;

            Console.WriteLine("\n");

            // Loop to print the memory dump to the consol ein "Hex Dump" typre format
            while (position < offset)
            {
                string line = "";
                line = "0x" + position.ToString("X8") + " ";
                string printBytes = "";
                string text = "";

                for(int i = 0; i < (buffWidth-1); i++)
                {
                    if(position >= offset) { break; }

                    printBytes += byteArray[position].ToString("X2") + " ";

                    if (char.IsLetterOrDigit((char)byteArray[position]) || char.IsPunctuation((char)byteArray[position]) || char.IsSymbol((char)byteArray[position]))
                    {
                        text += (char)byteArray[position];
                    }   
                    else
                    {
                        text += '.';
                    }
                    position++;

                }
                line += printBytes.PadRight(padding, ' ');
                line += " " + text;
                Console.WriteLine(line);

            }
        }

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

public static void ThreadList(string pidString)
        {
            int pid;

            // Check to make sure the input is an integer
            try
            {
                pid = Convert.ToInt32(pidString);

            }
            // If not call the help() funciton to return to the menu
            catch (Exception ex)
            {
                Console.WriteLine("Input not an integer.  Please try again");
                help();
                pid = 0;
            }

            try
            {
                // Get the process object for the pid input
                Process proc = Process.GetProcessById(pid);

                // Get the collection of threads for the process
                ProcessThreadCollection threads = proc.Threads;

                // List the threads to console
                foreach (ProcessThread thread in threads)
                {
                    // List the thread start address in hex format, the thread state, and the thread's base priority
                    Console.WriteLine("TID: {0}  Start Address: 0x{1}  Thread State: {2}  Base Priority: {3}", thread.Id, thread.StartAddress.ToString("X"), thread.ThreadState, thread.BasePriority);

                }

            }
            // If it fails call the help() function to return to the menu and alert the user to the failure
            catch(Exception ex)
            {
                Console.WriteLine("No Process Found with that Process ID. \nError: {0}", ex);
                help();
            }
        }

See More Examples