/// <summary> /// /// </summary> /// <returns></returns> public bool Connect() { if (this.IsConnected()) { return(true); } PROCESSENTRY32 pEntry = new PROCESSENTRY32(); pEntry.dwSize = Marshal.SizeOf(pEntry); uint procId = 0; int processId = -1; bool found = false; IntPtr snapshot = APIMethods.CreateToolhelp32Snapshot(SnapshotFlags.Process, procId); if (APIMethods.Process32First(snapshot, ref pEntry)) { while (APIMethods.Process32Next(snapshot, ref pEntry)) { if (pEntry.szExeFile.ToLower() == this._executableName) { processId = pEntry.th32ProcessID; found = true; break; } } } if (!found) { return(false); } IntPtr process = APIMethods.OpenProcess(ProccessAccess.AllAccess, false, processId); if (process == IntPtr.Zero) { return(false); } // Setting up the variable for the second argument for EnumProcessModules IntPtr[] hMods = new IntPtr[1024]; GCHandle gch = GCHandle.Alloc(hMods, GCHandleType.Pinned); // Don't forget to free this later IntPtr pModules = gch.AddrOfPinnedObject(); // Setting up the rest of the parameters for EnumProcessModules uint uiSize = (uint)(Marshal.SizeOf(typeof(IntPtr)) * (hMods.Length)); uint cbNeeded = 0; bool mainModuleFound = false; long baseAddress = 0; if (APIMethods.EnumProcessModulesEx(process, pModules, uiSize, out cbNeeded, DwFilterFlag.filter_all) == true) { Int32 uiTotalNumberofModules = (Int32)(cbNeeded / (Marshal.SizeOf(typeof(IntPtr)))); for (int i = 0; i < (int)uiTotalNumberofModules; i++) { StringBuilder strbld = new StringBuilder(1024); APIMethods.GetModuleFileNameEx(process, hMods[i], strbld, (int)(strbld.Capacity)); string moduleName = strbld.ToString(); if (Path.GetFileName(moduleName).ToLower() == this._executableName) { MODULEINFO mi = new MODULEINFO(); if (APIMethods.GetModuleInformation(process, hMods[i], out mi, Marshal.SizeOf(typeof(MODULEINFO)))) { baseAddress = (long)mi.lpBaseOfDll; mainModuleFound = true; break; } } } } gch.Free(); if (!mainModuleFound) { return(false); } this._mainModuleAddress = baseAddress; this._handle = process; this._gcProcessHandle = GCHandle.Alloc(this._handle, GCHandleType.Pinned); return(true); }