System.IntPtr.ToInt32()

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

889 Examples 7

19 Source : VirtualFileDataObject.cs
with MIT License
from Bassman2

[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
        void System.Runtime.InteropServices.ComTypes.IDataObject.SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release)
        {
            var handled = false;
            if ((formatIn.dwAspect == DVASPECT.DVASPECT_CONTENT) &&
                (formatIn.tymed == TYMED.TYMED_HGLOBAL) &&
                (medium.tymed == formatIn.tymed))
            {
                // Supported format; capture the data
                var ptr = NativeMethods.GlobalLock(medium.unionmember);
                if (IntPtr.Zero != ptr)
                {
                    try
                    {
                        var length = NativeMethods.GlobalSize(ptr).ToInt32();
                        var data = new byte[length];
                        Marshal.Copy(ptr, data, 0, length);
                        // Store it in our own format
                        SetData(formatIn.cfFormat, data);
                        handled = true;
                    }
                    finally
                    {
                        NativeMethods.GlobalUnlock(medium.unionmember);
                    }
                }

                // Release memory if we now own it
                if (release)
                {
                    Marshal.FreeHGlobal(medium.unionmember);
                }
            }

            // Handle synchronous mode
            if (!IsAsynchronous && (PERFORMEDDROPEFFECT == formatIn.cfFormat) && _inOperation)
            {
                // Call the end action and exit the operation
                if (null != _endAction)
                {
                    _endAction(this);
                }
                _inOperation = false;
            }

            // Throw if unhandled
            if (!handled)
            {
                throw new NotImplementedException();
            }
        }

19 Source : VirtualFileDataObject.cs
with MIT License
from Bassman2

[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Method doesn't decrease security.")]
        private DragDropEffects? GetDropEffect(short format)
        {
            // Get the most recent setting
            var dataObject = _dataObjects
                .Where(d =>
                    (format == d.FORMATETC.cfFormat) &&
                    (DVASPECT.DVASPECT_CONTENT == d.FORMATETC.dwAspect) &&
                    (TYMED.TYMED_HGLOBAL == d.FORMATETC.tymed))
                .LastOrDefault();
            if (null != dataObject)
            {
                // Read the value and return it
                var result = dataObject.GetData();
                if (NativeMethods.SUCCEEDED(result.Item2))
                {
                    var ptr = NativeMethods.GlobalLock(result.Item1);
                    if (IntPtr.Zero != ptr)
                    {
                        try
                        {
                            var length = NativeMethods.GlobalSize(ptr).ToInt32();
                            if (4 == length)
                            {
                                var data = new byte[length];
                                Marshal.Copy(ptr, data, 0, length);
                                return (DragDropEffects)(BitConverter.ToUInt32(data, 0));
                            }
                        }
                        finally
                        {
                            NativeMethods.GlobalUnlock(result.Item1);
                        }
                    }
                }
            }
            return null;
        }

19 Source : Utilities.cs
with Apache License 2.0
from beckzhu

[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public static System.Windows.Point GetPoint(IntPtr ptr)
        {
            var xy = unchecked(Environment.Is64BitProcess ? (uint)ptr.ToInt64() : (uint)ptr.ToInt32());
            var x = unchecked((short)xy);
            var y = unchecked((short)(xy >> 16));
            return new System.Windows.Point(x, y);
        }

19 Source : WindowMessageSink.cs
with Apache License 2.0
from beckzhu

private void ProcessWindowMessage(uint msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg != CallbackMessageId) return;

            switch (lParam.ToInt32())
            {
                case 0x200:
                    MouseEventReceived(MouseEvent.MouseMove);
                    break;

                case 0x201:
                    MouseEventReceived(MouseEvent.IconLeftMouseDown);
                    break;

                case 0x202:
                    if (!isDoubleClick)
                    {
                        MouseEventReceived(MouseEvent.IconLeftMouseUp);
                    }
                    isDoubleClick = false;
                    break;

                case 0x203:
                    isDoubleClick = true;
                    MouseEventReceived(MouseEvent.IconDoubleClick);
                    break;

                case 0x204:
                    MouseEventReceived(MouseEvent.IconRightMouseDown);
                    break;

                case 0x205:
                    MouseEventReceived(MouseEvent.IconRightMouseUp);
                    break;

                case 0x206:
                    //double click with right mouse button - do not trigger event
                    break;

                case 0x207:
                    MouseEventReceived(MouseEvent.IconMiddleMouseDown);
                    break;

                case 520:
                    MouseEventReceived(MouseEvent.IconMiddleMouseUp);
                    break;

                case 0x209:
                    //double click with middle mouse button - do not trigger event
                    break;

                case 0x402:
                    var listener = BalloonToolTipChanged;
                    if (listener != null) listener(true);
                    break;

                case 0x403:
                case 0x404:
                    listener = BalloonToolTipChanged;
                    if (listener != null) listener(false);
                    break;

                case 0x405:
                    MouseEventReceived(MouseEvent.BalloonToolTipClicked);
                    break;

                case 0x406:
                    listener = ChangeToolTipStateRequest;
                    if (listener != null) listener(true);
                    break;

                case 0x407:
                    listener = ChangeToolTipStateRequest;
                    if (listener != null) listener(false);
                    break;

                default:
                    Debug.WriteLine("Unhandled NotifyIcon message ID: " + lParam);
                    break;
            }
        }

19 Source : RemoteControl_rdp.xaml.cs
with Apache License 2.0
from beckzhu

private int WinRdpClientProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == 15)
            {
                User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
                Graphics grap = Graphics.FromHwnd(hwnd);
                grap.Clear(Color.White);
                return 0;
            }
            if (msg == 20)
            {
                Graphics grap = Graphics.FromHwnd(hwnd);
                grap.Clear(Color.White);
                return 0;
            }
            if (msg == 133)
            {
                User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
                return 0;
            }
            if (msg == 512)//WM_MOUSEMOVE
            {
                int num = lParam.ToInt32();
                MouseMoveProc?.Invoke(CommonServices.LOWORD(num), CommonServices.HIWORD(num));
            }
            return User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
        }

19 Source : RemoteControl_rdp.xaml.cs
with Apache License 2.0
from beckzhu

private int WinInRdpClientProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == 512)//WM_MOUSEMOVE
            {
                int num = lParam.ToInt32();
                User32.GetWindowRect(hwnd, out var chileRect);
                User32.GetWindowRect(_topWindowHwnd, out var parentRect);
                int x = chileRect.Left - parentRect.Left;
                int y = chileRect.Top - parentRect.Top;
                MouseMoveProc?.Invoke(CommonServices.LOWORD(num) + x, CommonServices.HIWORD(num) + y);
            }
            if (msg == 513)//WM_LBUTTONDOWN
            {
                User32.SetFocus(hwnd);
            }
            return User32.CallWindowProc(_oldInRdpClientWinProc, hwnd, msg, wParam, lParam);
        }

19 Source : Launcher.cs
with GNU General Public License v3.0
from belowaverage-org

protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0312 && m.WParam.ToInt32() == 0) //WM_HOTKEY //ALT + S
            {
                CenterToScreen();
                FadeIn();
            }
            if (m.Msg == 0x0312 && m.WParam.ToInt32() == 1) //WM_HOTKEY //ALT + E
            {
                TcMiOpenExplorer_Click(null, null);
            }
            if (m.Msg == 0x0312 && m.WParam.ToInt32() == 2) //WM_HOTKEY //ALT + R
            {
                TcMIOpenRun_Click(null, null);
            }
            if (m.Msg == 0x0100 && m.WParam.ToInt32() == 0x1B) //WM_KEYDOWN //ESC
            {
                FadeOut();
            }
            if (m.Msg == 0x6) //WM_ACTIVATE
            {
                MARGINS margins;
                margins.cxLeftWidth = 1;
                margins.cxRightWidth = 1;
                margins.cyBottomHeight = 1;
                margins.cyTopHeight = 1;
                _ = DwmExtendFrameIntoClientArea(Handle, ref margins);
            }
            if (m.Msg == 0x1) //WM_CREATE
            {
                SetWindowPos(Handle, IntPtr.Zero, Left, Top, Width, Height, 0x20); //SWP_FRAMECHANGED
            }
            if (m.Msg == 0x83 && m.WParam == (IntPtr)1) //WM_NCCALCSIZE
            {
                return;
            }
            if (m.Msg == 0x84) //WM_NCHITTEST
            {

            }
            base.WndProc(ref m);
        }

19 Source : DetourGenerator.cs
with GNU Lesser General Public License v2.1
from BepInEx

public static byte[] GenerateAbsoluteJump(IntPtr targetAddress, IntPtr currentAddress, Architecture arch)
        {
            byte[] jmpBytes;

            if (arch == Architecture.X64)
            {
                jmpBytes = new byte[]
                {
                    0xFF, 0x25, 0x00, 0x00, 0x00, 0x00,            // FF25 00000000: JMP [RIP+6]
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
                };

                Array.Copy(BitConverter.GetBytes(targetAddress.ToInt64()), 0, jmpBytes, 6, 8);
            }
            else
            {
                jmpBytes = new byte[]
                {
                    0xE9,                  // E9: JMP rel destination
                    0x00, 0x00, 0x00, 0x00 // Relative destination address
                };

                Array.Copy(BitConverter.GetBytes(targetAddress.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes,
                           1, 4);
            }

            return jmpBytes;
        }

19 Source : Patcher.cs
with MIT License
from betenner

public static bool Start(string d2rPath = "Game.exe", int crashDelay = 25, string d2rargs = "")
        {
            if (!File.Exists(d2rPath))
            {
                Program.ConsolePrint($"Error, file '{d2rPath}' does not exist!", ConsoleColor.Red);
                Program.ConsolePrint("Usage: D2ROffline.exe PATH_TO_GAMEDOTEXE", ConsoleColor.White);
                return false;
            }

            Program.ConsolePrint("Launching game...");
            var pInfo = new ProcessStartInfo(d2rPath);

            if (d2rargs != "")
                pInfo.Arguments = d2rargs;
            else
                Program.ConsolePrint("Extra parameters not found. Proceeding...", ConsoleColor.White); // not to obvious color or ppl may freak out

            var d2r = Process.Start(pInfo);

            // wait for proc to properly enter userland to bypreplaced first few anti-cheating checks
            Program.ConsolePrint("Process started...");
            IntPtr hProcess = OpenProcess(ProcessAccessFlags.PROCESS_ALL_ACCESS, false, d2r.Id);
            Program.ConsolePrint("Opening process...");

            if (hProcess == IntPtr.Zero)
            {
                Program.ConsolePrint("Failed on OpenProcess. Handle is invalid.", ConsoleColor.Red);
                return false;
            }

            // pre setup
            WaitForData(hProcess, d2r.MainModule.BaseAddress, 0x22D8858);
            Thread.Sleep(crashDelay); // NOTE: getting crash? extend this delay!

            // suspend process
            Program.ConsolePrint("Suspending process...");
            NtSuspendProcess(hProcess);
            Program.ConsolePrint("Process suspended");

            X509Certificate data = X509Certificate.CreateFromSignedFile(d2rPath);
            if(!data.Subject.Contains(" Entertainment, "))
            {
                Program.ConsolePrint("Error, the target process is not a game?");
                return false;
            }

            if (VirtualQueryEx(hProcess, d2r.MainModule.BaseAddress, out MEMORY_BASIC_INFORMATION basicInformation, Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) == 0)
            {
                Program.ConsolePrint("Failed on VirtualQueryEx. Return is 0 bytes.", ConsoleColor.Red);
                return false;
            }

            IntPtr regionBase = basicInformation.baseAddress;
            IntPtr regionSize = basicInformation.regionSize;

            Program.ConsolePrint("Remapping process..");
            IntPtr addr = RemapMemoryRegion(hProcess, regionBase, regionSize.ToInt32(), MemoryProtectionConstraints.PAGE_EXECUTE_READWRITE);

            Program.ConsolePrint("Resuming process..");
            NtResumeProcess(hProcess);
            CloseHandle(hProcess);
            return true;
        }

19 Source : ProtectionHelper.cs
with Apache License 2.0
from bezzad

public static bool DetectSandbox()
        {
            return GetModuleHandle("SbieDll.dll").ToInt32() != 0;
        }

19 Source : AntiDump.cs
with Apache License 2.0
from bezzad

[SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")]
        public static void ProtectDump()
        {
            var process = System.Diagnostics.Process.GetCurrentProcess();
            if (process.MainModule != null)
            {
                var baseAddress = process.MainModule.BaseAddress;
                var dwpeheader = System.Runtime.InteropServices.Marshal.ReadInt32((IntPtr)(baseAddress.ToInt32() + 0x3C));
                var wnumberofsections = System.Runtime.InteropServices.Marshal.ReadInt16((IntPtr)(baseAddress.ToInt32() + dwpeheader + 0x6));

                EraseSection(baseAddress, 30);

                for (var i = 0; i < Peheaderdwords.Length; i++)
                {
                    EraseSection((IntPtr)(baseAddress.ToInt32() + dwpeheader + Peheaderdwords[i]), 4);
                }

                for (var i = 0; i < Peheaderwords.Length; i++)
                {
                    EraseSection((IntPtr)(baseAddress.ToInt32() + dwpeheader + Peheaderwords[i]), 2);
                }

                for (var i = 0; i < Peheaderbytes.Length; i++)
                {
                    EraseSection((IntPtr)(baseAddress.ToInt32() + dwpeheader + Peheaderbytes[i]), 1);
                }

                var x = 0;
                var y = 0;

                while (x <= wnumberofsections)
                {
                    if (y == 0)
                    {
                        EraseSection((IntPtr)((baseAddress.ToInt32() + dwpeheader + 0xFA + (0x28 * x)) + 0x20), 2);
                    }

                    EraseSection((IntPtr)((baseAddress.ToInt32() + dwpeheader + 0xFA + (0x28 * x)) + Sectiontabledwords[y]), 4);

                    y++;

                    if (y == Sectiontabledwords.Length)
                    {
                        x++;
                        y = 0;
                    }
                }
            }
        }

19 Source : HandleBase.cs
with MIT License
from bibigone

public override int GetHashCode()
            => handle.ToInt32();

19 Source : KeyboardHook.cs
with MIT License
from Blacklock

private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam) {
			if (nCode >= 0) {
				int iwParam = wParam.ToInt32();

				if ((iwParam == WM_KEYDOWN || iwParam == WM_SYSKEYDOWN))
					if (KeyDown != null)
						KeyDown((VKeys)Marshal.ReadInt32(lParam));
				if ((iwParam == WM_KEYUP || iwParam == WM_SYSKEYUP))
					if (KeyUp != null)
						KeyUp((VKeys)Marshal.ReadInt32(lParam));
			}

			return CallNextHookEx(hookID, nCode, wParam, lParam);
		}

19 Source : Autofarm.cs
with MIT License
from Blacklock

private static string ViewHandleName(WS.SYSTEM_HANDLE_INFORMATION shHandle, Process process) {
			// handleInfoStruct is the struct that contains data about our handle
			// targetProcess is the process where the handle resides
			// DUP_HANDLE (0x40) might also work
			IntPtr sourceProcessHandle = OpenProcess(0x1F0FFF, false, process.Id);
			IntPtr targetHandle = IntPtr.Zero;

			// We create a duplicate of the handle so that we can query more information about it
			if (!DuplicateHandle(sourceProcessHandle, shHandle.Handle, GetCurrentProcess(), out targetHandle, 0, false, 0x2)) {
				return null;
			}

			// Buffers that the query results get sent to
			IntPtr basicQueryData = IntPtr.Zero;

			// Query result structs
			WS.OBJECT_BASIC_INFORMATION basicInformationStruct = new WS.OBJECT_BASIC_INFORMATION();
			WS.OBJECT_NAME_INFORMATION nameInformationStruct = new WS.OBJECT_NAME_INFORMATION();

			basicQueryData = Marshal.AllocHGlobal(Marshal.SizeOf(basicInformationStruct));

			int nameInfoLength = 0; // Size of information returned to us
			NtQueryObject(targetHandle, 0, basicQueryData, Marshal.SizeOf(basicInformationStruct), ref nameInfoLength);

			// Insert buffer data into a struct and free the buffer
			basicInformationStruct = (WS.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(basicQueryData, basicInformationStruct.GetType());
			Marshal.FreeHGlobal(basicQueryData);

			// The basicInformationStruct contains data about the name's length
			// TODO: We could probably skip querying for OBJECT_BASIC_INFORMATION
			nameInfoLength = basicInformationStruct.NameInformationLength;

			// Allocate buffer for the name now that we know its size
			IntPtr nameQueryData = Marshal.AllocHGlobal(nameInfoLength);

			// Object information clreplaced: 1
			// If it's incorrect, it returns STATUS_INFO_LENGTH_MISMATCH (0xc0000004)
			int result;
			while ((uint)(result = NtQueryObject(targetHandle, 1, nameQueryData, nameInfoLength, ref nameInfoLength)) == 0xc0000004) {
				Marshal.FreeHGlobal(nameQueryData);
				nameQueryData = Marshal.AllocHGlobal(nameInfoLength);
			}
			nameInformationStruct = (WS.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(nameQueryData, nameInformationStruct.GetType());

			IntPtr handlerName;

			if (Is64Bits()) {
				handlerName = new IntPtr(Convert.ToInt64(nameInformationStruct.Name.Buffer.ToString(), 10) >> 32);
			} else {
				handlerName = nameInformationStruct.Name.Buffer;
			}

			if (handlerName != IntPtr.Zero) {
				byte[] baTemp2 = new byte[nameInfoLength];
				try {
					Marshal.Copy(handlerName, baTemp2, 0, nameInfoLength);
					return Marshal.PtrToStringUni(Is64Bits() ? new IntPtr(handlerName.ToInt64()) : new IntPtr(handlerName.ToInt32()));
				}
				catch (AccessViolationException) {
					return null;
				}
				finally {
					Marshal.FreeHGlobal(nameQueryData);
					CloseHandle(targetHandle);
				}
			}
			return null;
		}

19 Source : Autofarm.cs
with MIT License
from Blacklock

private void CloseProcessHandles(Process growtopia) { // We need to remove handlers from the last process
			Console.WriteLine("Starting handle magic...");
			statusMessage.Text = "Querying system handle information...";
			int nLength = 0;
			IntPtr handlePointer = IntPtr.Zero;
			int sysInfoLength = 0x10000; // How much to allocate to returned data
			IntPtr infoPointer = Marshal.AllocHGlobal(sysInfoLength);
			// 0x10 = SystemHandleInformation, an undoreplacedented SystemInformationClreplaced
			uint result; // NtQuerySystemInformation won't give us the correct buffer size, so we guess it
						 // replacedign result of NtQuerySystemInformation to this variable and check if the buffer size is correct
						 // If it's incorrect, it returns STATUS_INFO_LENGTH_MISMATCH (0xc0000004)
			while ((result = NtQuerySystemInformation(0x10, infoPointer, sysInfoLength, ref nLength)) == 0xc0000004) {
				sysInfoLength = nLength;
				Marshal.FreeHGlobal(infoPointer);
				infoPointer = Marshal.AllocHGlobal(nLength);
			}

			byte[] baTemp = new byte[nLength];
			// Copy the data from unmanaged memory to managed 1-byte uint array
			Marshal.Copy(infoPointer, baTemp, 0, nLength);
			// Do we even need the two statements above??? Look into this later.

			long sysHandleCount = 0; // How many handles there are total
			if (Is64Bits()) {
				sysHandleCount = Marshal.ReadInt64(infoPointer);
				handlePointer = new IntPtr(infoPointer.ToInt64() + 8); // Points in bits at the start of a handle
			} else {
				sysHandleCount = Marshal.ReadInt32(infoPointer);
				handlePointer = new IntPtr(infoPointer.ToInt32() + 4); // Ignores 4 first bits instead of 8
			}

			statusMessage.Text = "Query received, processing the " + sysHandleCount + " results.";

			WS.SYSTEM_HANDLE_INFORMATION handleInfoStruct; // The struct to hold info about a single handler

			List<WS.SYSTEM_HANDLE_INFORMATION> handles = new List<WS.SYSTEM_HANDLE_INFORMATION>();
			for (long i = 0; i < sysHandleCount; i++) { // Iterate over handle structs in the handle struct list
				handleInfoStruct = new WS.SYSTEM_HANDLE_INFORMATION();
				if (Is64Bits()) {
					handleInfoStruct = (WS.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(handlePointer, handleInfoStruct.GetType()); // Convert to struct
					handlePointer = new IntPtr(handlePointer.ToInt64() + Marshal.SizeOf(handleInfoStruct) + 8); // point 8 bits forward to the next handle
				} else {
					handleInfoStruct = (WS.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(handlePointer, handleInfoStruct.GetType());
					handlePointer = new IntPtr(handlePointer.ToInt64() + Marshal.SizeOf(handleInfoStruct));
				}

				if (handleInfoStruct.ProcessID != growtopia.Id) { // Check if current handler is from Growtopia
					continue; // If it's not from Growtopia, just skip it
				}

				string handleName = ViewHandleName(handleInfoStruct, growtopia);
				// TODO: Looks like the mutant session number is different for different PCs
				// Maybe just check if the string contains basenamedobjects/growtopia and starts with sessions?
				if (handleName != null && handleName.StartsWith(@"\Sessions\") && handleName.EndsWith(@"\BaseNamedObjects\Growtopia")) {
					handles.Add(handleInfoStruct);
					Console.WriteLine("PID {0,7} Pointer {1,12} Type {2,4} Name {3}", handleInfoStruct.ProcessID.ToString(),
																					  handleInfoStruct.Object_Pointer.ToString(),
																					  handleInfoStruct.ObjectTypeNumber.ToString(),
																					  handleName);
				} else {
					continue; // This is not a handle we're looking for
				}
				
			}

			Console.WriteLine("Closing mutexes?");
			foreach (WS.SYSTEM_HANDLE_INFORMATION handle in handles) {
				CloseMutex(handle);
			}

			statusMessage.Text = "Query finished, " + sysHandleCount + " results processed.";
			Console.WriteLine("Handle closed.");
		}

19 Source : PlatformUtils.cs
with MIT License
from BleuBleu

public static MouseEventArgs ConvertHorizontalMouseWheelMessage(Control ctrl, System.Windows.Forms.Message m)
        {
            // TODO: Test hi-dpi and things like this.
            short x = (short)((m.LParam.ToInt32() >> 0) & 0xffff);
            short y = (short)((m.LParam.ToInt32() >> 16) & 0xffff);
            short delta = (short)((m.WParam.ToInt32() >> 16) & 0xffff);
            var clientPos = ctrl.PointToClient(new Point(x, y));

            return new MouseEventArgs(MouseButtons.None, 1, clientPos.X, clientPos.Y, delta);
        }

19 Source : ProcessUtil.cs
with MIT License
from blish-hud

private static string GetCommandLineInternal(IntPtr hProcess) {
            byte[] buffer = Array.Empty<byte>();

            // Preplaced 0 for length, required length is returned in bufSz
            NTSTATUS status = NtQueryInformationProcess(hProcess, PROCESSINFOCLreplaced.ProcessCommandLineInformation, buffer, buffer.Length, out IntPtr bufSz);
            if (status != NTSTATUS.STATUS_INFO_LENGTH_MISMATCH) {
                throw new Win32Exception();
            }

            // Allocate a buffer
            buffer = new byte[bufSz.ToInt32()];
            status = NtQueryInformationProcess(hProcess, PROCESSINFOCLreplaced.ProcessCommandLineInformation, buffer, buffer.Length, out _);
            if (status != NTSTATUS.STATUS_SUCCESS) {
                throw new Win32Exception();
            }

            // The returned buffer is a UNICODE_STRING structure - the entire string is contained there.
            int offset = Marshal.SizeOf<UNICODE_STRING>();
            UNICODE_STRING str = MemoryMarshal.Read<UNICODE_STRING>(buffer);
            return Encoding.Unicode.GetString(buffer, offset, str.length);
        }

19 Source : LuaDLL.cs
with MIT License
from blueberryzzz

public static string lua_tostring(IntPtr L, int index)
		{
            IntPtr strlen;

            IntPtr str = lua_tolstring(L, index, out strlen);
            if (str != IntPtr.Zero)
			{
#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
                int len = strlen.ToInt32();
                byte[] buffer = new byte[len];
                Marshal.Copy(str, buffer, 0, len);
                return Encoding.UTF8.GetString(buffer);
#else
                string ret = Marshal.PtrToStringAnsi(str, strlen.ToInt32());
                if (ret == null)
                {
                    int len = strlen.ToInt32();
                    byte[] buffer = new byte[len];
                    Marshal.Copy(str, buffer, 0, len);
                    return Encoding.UTF8.GetString(buffer);
                }
                return ret;
#endif
            }
            else
			{
                return null;
			}
		}

19 Source : LuaDLL.cs
with MIT License
from blueberryzzz

public static byte[] lua_tobytes(IntPtr L, int index)//[-0, +0, m]
        {
            if (lua_type(L, index) == LuaTypes.LUA_TSTRING)
            { 
                IntPtr strlen;
                IntPtr str = lua_tolstring(L, index, out strlen);
                if (str != IntPtr.Zero)
                {
                    int buff_len = strlen.ToInt32();
                    byte[] buffer = new byte[buff_len];
                    Marshal.Copy(str, buffer, 0, buff_len);
                    return buffer;
                }
            }
            return null;
        }

19 Source : MyMainForm.cs
with MIT License
from BluePointLilac

protected override void WndProc(ref Message m)
        {
            const int WM_NCLBUTTONDBLCLK = 0x00A3;
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_MAXIMIZE = 0xF030;
            const int SC_MINIMIZE = 0xF020;
            const int SC_RESTORE = 0xF120;
            const int SC_MOVE = 0xF012;
            const int SC_SIZE = 0xF000;
            const int HT_CAPTION = 0x2;
            bool suspend = false;//临时挂起MainBody
            switch(m.Msg)
            {
                case WM_SYSCOMMAND:
                    switch(m.WParam.ToInt32())
                    {
                        //解决控件过多移动窗体时延迟问题
                        case SC_MOVE:
                        //解决控件过多调整窗体大小时延迟问题
                        case SC_SIZE:
                            suspend = this.SuspendMainBodyWhenMove; break;
                        //解决控件过多最大化、最小化、还原重绘卡顿问题
                        case SC_RESTORE:
                        case SC_MINIMIZE:
                        case SC_MAXIMIZE:
                            suspend = this.SuspendMainBodyWhenResize; break;
                    }
                    break;
                case WM_NCLBUTTONDBLCLK:
                    switch(m.WParam.ToInt32())
                    {
                        //双击标题栏最大化和还原窗口
                        case HT_CAPTION:
                            suspend = this.SuspendMainBodyWhenResize; break;
                    }
                    break;
            }
            if(suspend)
            {
                this.SuspendLayout();
                MainBody.SuspendLayout();
                this.Controls.Remove(MainBody);
                base.WndProc(ref m);
                this.Controls.Add(MainBody);
                MainBody.BringToFront();
                MainBody.ResumeLayout();
                this.ResumeLayout();
            }
            else base.WndProc(ref m);
        }

19 Source : Video.cs
with MIT License
from BoonyaCSharp-ASP

public void StarKinescope(string path)
        {
            strFileName = path;
            string dir = path.Remove(path.LastIndexOf("\\"));
            if (!File.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            int hBmp = Marshal.StringToHGlobalAnsi(path).ToInt32();
            bool b = VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_FILE_SET_CAPTURE_FILE, 0, hBmp);
            b = VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SEQUENCE, 0, 0);
        }

19 Source : Video.cs
with MIT License
from BoonyaCSharp-ASP

public void GrabImage(IntPtr hWndC, string path)
        {
            IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
            VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
        }

19 Source : Struct.cs
with GNU General Public License v3.0
from BorjaMerino

private static byte[] ConvertEndian<T>(byte[] data) {
            Type type = typeof(T);
            FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            EndianAttribute endian = null;

            if (type.GetTypeInfo().IsDefined(typeof(EndianAttribute), false)) {
                endian = (EndianAttribute) type.GetTypeInfo().GetCustomAttributes(typeof(EndianAttribute), false).First();
            }

            foreach (FieldInfo field in fields) {
                if (endian == null && !field.IsDefined(typeof(EndianAttribute), false)) {
                    continue;
                }

                int offset = Marshal.OffsetOf<T>(field.Name).ToInt32();
                #pragma warning disable 618
                int length = Marshal.SizeOf(field.FieldType);
                #pragma warning restore 618
                endian = endian ?? (EndianAttribute) field.GetCustomAttributes(typeof(EndianAttribute), false).First();

                if (endian.Endianness == Endianness.Big && BitConverter.IsLittleEndian ||
                        endian.Endianness == Endianness.Little && !BitConverter.IsLittleEndian) {
                    Array.Reverse(data, offset, length);
                }
            }

            return data;
        }

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

[DebuggerStepThrough]
        private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Single instance or Hotkey --> Show window
            if (msg == SingleInstance.WM_SHOWME || msg == WmHotkey && wParam.ToInt32() == 1)
            {
                ShowWindowAction();
                handled = true;
            }

            return IntPtr.Zero;
        }

19 Source : ProgressDialog.cs
with MIT License
from bruhov

public static IntPtr SetWindowLongPtr(IntPtr hWnd, GWL nIndex, IntPtr dwNewLong)
        {
            if (IntPtr.Size == 8)
                return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
            else
                return new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong.ToInt32()));
        }

19 Source : Memory.cs
with Apache License 2.0
from bytecodealliance

public void WriteIntPtr(IStore store, int address, IntPtr value)
        {
            if (IntPtr.Size == 4)
            {
                WriteInt32(store, address, value.ToInt32());
            }
            else
            {
                WriteInt64(store, address, value.ToInt64());
            }
        }

19 Source : Native.cs
with MIT License
from C1rdec

public static IntPtr SetWindowLongPtr(HandleRef hWnd, int nIndex, IntPtr dwNewLong)
        {
            if (IntPtr.Size == 8)
                return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
            else
                return new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong.ToInt32()));
        }

19 Source : AppBarWindow.cs
with Apache License 2.0
from cairoshell

protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == AppBarMessageId && AppBarMessageId != -1)
            {
                switch ((NativeMethods.AppBarNotifications)wParam.ToInt32())
                {
                    case NativeMethods.AppBarNotifications.PosChanged:
                        if (Orientation == Orientation.Vertical)
                        {
                            _appBarManager.ABSetPos(this, DesiredWidth * DpiScale, ActualHeight * DpiScale, AppBarEdge);
                        }
                        else
                        {
                            _appBarManager.ABSetPos(this, ActualWidth * DpiScale, DesiredHeight * DpiScale, AppBarEdge);
                        }
                        break;

                    case NativeMethods.AppBarNotifications.WindowArrange:
                        if ((int)lParam != 0) // before
                        {
                            Visibility = Visibility.Collapsed;
                        }
                        else // after
                        {
                            Visibility = Visibility.Visible;
                        }

                        break;
                }
                handled = true;
            }
            else if (msg == (int)NativeMethods.WM.ACTIVATE && EnableAppBar && !EnvironmentHelper.IsAppRunningreplacedhell && !AllowClose)
            {
                _appBarManager.AppBarActivate(hwnd);
            }
            else if (msg == (int)NativeMethods.WM.WINDOWPOSCHANGING)
            {
                // Extract the WINDOWPOS structure corresponding to this message
                NativeMethods.WINDOWPOS wndPos = NativeMethods.WINDOWPOS.FromMessage(lParam);

                // Determine if the z-order is changing (absence of SWP_NOZORDER flag)
                // If we are intentionally trying to become topmost, make it so
                if (IsRaising && (wndPos.flags & NativeMethods.SetWindowPosFlags.SWP_NOZORDER) == 0)
                {
                    // Sometimes Windows thinks we shouldn't go topmost, so poke here to make it happen.
                    wndPos.hwndInsertAfter = (IntPtr)NativeMethods.WindowZOrder.HWND_TOPMOST;
                    wndPos.UpdateMessage(lParam);
                }
            }
            else if (msg == (int)NativeMethods.WM.WINDOWPOSCHANGED && EnableAppBar && !EnvironmentHelper.IsAppRunningreplacedhell && !AllowClose)
            {
                _appBarManager.AppBarWindowPosChanged(hwnd);
            }
            else if (msg == (int)NativeMethods.WM.DPICHANGED)
            {
                if (Screen.Primary)
                {
                    DpiHelper.DpiScale = (wParam.ToInt32() & 0xFFFF) / 96d;
                }

                DpiScale = (wParam.ToInt32() & 0xFFFF) / 96d;

                ProcessScreenChange(ScreenSetupReason.DpiChange);
            }
            else if (msg == (int)NativeMethods.WM.DISPLAYCHANGE)
            {
                ProcessScreenChange(ScreenSetupReason.DisplayChange);
                handled = true;
            }
            else if (msg == (int)NativeMethods.WM.DEVICECHANGE && (int)wParam == 0x0007)
            {
                ProcessScreenChange(ScreenSetupReason.DeviceChange);
                handled = true;
            }
            else if (msg == (int)NativeMethods.WM.DWMCOMPOSITIONCHANGED)
            {
                ProcessScreenChange(ScreenSetupReason.DwmChange);
                handled = true;
            }
            
            return IntPtr.Zero;
        }

19 Source : NativeMethods.Ole32.cs
with Apache License 2.0
from cairoshell

private byte[] GetDataBytes()
            {
                byte[] ret = new byte[IntPtr.Size + sizeof(int)];
                if (IntPtr.Size == 4)
                    BitConverter.GetBytes(p.ToInt32()).CopyTo(ret, 0);
                else if (IntPtr.Size == 8)
                    BitConverter.GetBytes(p.ToInt64()).CopyTo(ret, 0);
                BitConverter.GetBytes(p2).CopyTo(ret, IntPtr.Size);
                return ret;
            }

19 Source : EventInput.cs
with MIT License
from ccajas

static IntPtr HookProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
        {
            IntPtr returnCode = CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);

            switch (msg)
            {
                case WM_GETDLGCODE:
                    returnCode = (IntPtr)(returnCode.ToInt32() | DLGC_WANTALLKEYS);
                    break;

                case WM_KEYDOWN:
                    if (KeyDown != null)
                        KeyDown(null, new KeyEventArgs((Keys)wParam));
                    break;

                case WM_KEYUP:
                    if (KeyUp != null)
                        KeyUp(null, new KeyEventArgs((Keys)wParam));
                    break;

                case WM_CHAR:
                    if (CharEntered != null)
                        CharEntered(null, new CharacterEventArgs((char)wParam, lParam.ToInt32()));
                    break;

                case WM_IME_SETCONTEXT:
                    if (wParam.ToInt32() == 1)
                        ImmreplacedociateContext(hWnd, hIMC);
                    break;

                case WM_INPUTLANGCHANGE:
                    ImmreplacedociateContext(hWnd, hIMC);
                    returnCode = (IntPtr)1;
                    break;
            }

            return returnCode;
        }

19 Source : HideTaskmgrList.cs
with GNU General Public License v3.0
from cdians

public void Hide(IntPtr p_ListViewIntPtr)
        {
            IntPtr _ControlIntPtr = p_ListViewIntPtr;

            int _ItemCount = Win32API.SendMessage(p_ListViewIntPtr, 0x1004, 0, 0);

            Win32API.ProcessAccessType _Type;
            _Type = Win32API.ProcessAccessType.PROCESS_VM_OPERATION | Win32API.ProcessAccessType.PROCESS_VM_READ | Win32API.ProcessAccessType.PROCESS_VM_WRITE;

            IntPtr _ProcessIntPtr = Win32API.OpenProcess(_Type, 1, (uint)m_ProcessID);

            IntPtr _Out = IntPtr.Zero;
            for (int z = 0; z != _ItemCount; z++)
            {

                //分配一个内存地址 保存进程的应用程序名称  
                IntPtr _StrBufferMemory = Win32API.VirtualAllocEx(_ProcessIntPtr, 0, 255, Win32API.MEM_COMMIT.MEM_COMMIT, Win32API.MEM_PAGE.PAGE_READWRITE);

                byte[] _OutBytes = new byte[40];  //定义结构体 (LVITEM)          

                byte[] _StrIntPtrAddress = BitConverter.GetBytes(_StrBufferMemory.ToInt32());
                _OutBytes[20] = _StrIntPtrAddress[0];
                _OutBytes[21] = _StrIntPtrAddress[1];
                _OutBytes[22] = _StrIntPtrAddress[2];
                _OutBytes[23] = _StrIntPtrAddress[3];
                _OutBytes[24] = 255;

                //给结构体分配内存  
                IntPtr _Memory = Win32API.VirtualAllocEx(_ProcessIntPtr, 0, _OutBytes.Length, Win32API.MEM_COMMIT.MEM_COMMIT, Win32API.MEM_PAGE.PAGE_READWRITE);
                //把数据传递给结构体 (LVITEM)    
                Win32API.WriteProcessMemory(_ProcessIntPtr, _Memory, _OutBytes, (uint)_OutBytes.Length, out _Out);

                //发送消息获取结构体数据  
                Win32API.SendMessage(p_ListViewIntPtr, 0x102D, z, _Memory);

                //获取结构体数据  
                Win32API.ReadProcessMemory(_ProcessIntPtr, _Memory, _OutBytes, (uint)_OutBytes.Length, out _Out);

                //获取结构体 pszText的地址  
                IntPtr _ValueIntPtr = new IntPtr(BitConverter.ToInt32(_OutBytes, 20));

                byte[] _TextBytes = new byte[255];  //获取pszText的数据  
                Win32API.ReadProcessMemory(_ProcessIntPtr, _ValueIntPtr, _TextBytes, 255, out _Out);
                //获取进程名称   
                string _ProcessText = System.Text.Encoding.Default.GetString(_TextBytes).Trim(new Char[] { '\0' });
                //释放内存  
                Win32API.VirtualFreeEx(_ProcessIntPtr, _StrBufferMemory, 0, Win32API.MEM_COMMIT.MEM_RELEASE);
                Win32API.VirtualFreeEx(_ProcessIntPtr, _Memory, 0, Win32API.MEM_COMMIT.MEM_RELEASE);

                if (_ProcessText == m_ProcessName)
                {
                    Win32API.SendMessage(p_ListViewIntPtr, 0x1008, z, 0);
                }
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from cdmxz

private void ThreadPreprocessMessageMethod(ref System.Windows.Interop.MSG m, ref bool handled)
        {
            if (!handled)
            {
                if (m.message == 0x0312)// 如果m.message的值为0x0312那么表示用户按下了热键
                {
                    if (m.wParam.ToInt32() == REC_HOT_KEY_ID)
                        Record();
                    else if (m.wParam.ToInt32() == EXE_HOT_KEY_ID)
                        Execute();
                    handled = true;
                }
            }
        }

19 Source : NativeMethods.cs
with Apache License 2.0
from cdy816

internal static int GetSize(uv_handle_type handleType) => uv_handle_size(handleType).ToInt32();

19 Source : NativeMethods.cs
with Apache License 2.0
from cdy816

internal static int GetSize(uv_req_type requestType) => uv_req_size(requestType).ToInt32();

19 Source : PipeHandle.cs
with Apache License 2.0
from cdy816

public string GetSocketName()
        {
            this.Validate();
            var buf = stackalloc byte[NameBufferSize];
            var length = (IntPtr)NameBufferSize;
            var ptr = (IntPtr)buf;

            int result = NativeMethods.uv_pipe_getsockname(this.Handle, ptr, ref length);
            NativeMethods.ThrowIfError(result);

            string socketName = Marshal.PtrToStringAnsi(ptr, length.ToInt32());
            return socketName;
        }

19 Source : PipeHandle.cs
with Apache License 2.0
from cdy816

public string GetPeerName()
        {
            this.Validate();

            var buf = stackalloc byte[NameBufferSize];
            var length = (IntPtr)NameBufferSize;
            var ptr = (IntPtr)buf;

            int result = NativeMethods.uv_pipe_getpeername(this.Handle, ptr, ref length);
            NativeMethods.ThrowIfError(result);

            string peerName = Marshal.PtrToStringAnsi(ptr, length.ToInt32());
            return peerName;
        }

19 Source : TcpHandle.cs
with Apache License 2.0
from cdy816

public int SendBufferSize(int value)
        {
            Contract.Requires(value >= 0);

            this.Validate();
            var size = (IntPtr)value;
            int result = NativeMethods.uv_send_buffer_size(this.Handle, ref size);
            NativeMethods.ThrowIfError(result);

            return size.ToInt32();
        }

19 Source : TcpHandle.cs
with Apache License 2.0
from cdy816

public int ReceiveBufferSize(int value)
        {
            Contract.Requires(value >= 0);

            this.Validate();
            var size = (IntPtr)value;

            int result = NativeMethods.uv_recv_buffer_size(this.Handle, ref size);
            NativeMethods.ThrowIfError(result);

            return size.ToInt32();
        }

19 Source : UnixApi.cs
with Apache License 2.0
from cdy816

internal static unsafe bool GetReuseAddress(IntPtr socket)
        {
            int value = 0;
            int status = 0;
            int optLen = sizeof(int);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                status = getsockopt(socket.ToInt32(), SOL_SOCKET_LINUX, SO_REUSEADDR_LINUX, (byte*)&value, &optLen);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                status = getsockopt(socket.ToInt32(), SOL_SOCKET_OSX, SO_REUSEADDR_OSX, (byte*)&value, &optLen);
            }
            if (status != 0)
            {
                throw new SocketException(Marshal.GetLastWin32Error());
            }

            return value != 0;
        }

19 Source : UnixApi.cs
with Apache License 2.0
from cdy816

internal static unsafe void SetReuseAddress(IntPtr socket, int value)
        {
            int status = 0;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                status = setsockopt(socket.ToInt32(), SOL_SOCKET_LINUX, SO_REUSEADDR_LINUX, (IntPtr)(&value), sizeof(int));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                status = setsockopt(socket.ToInt32(), SOL_SOCKET_OSX, SO_REUSEADDR_OSX, (IntPtr)(&value), sizeof(int));
            }
            if (status != 0)
            {
                throw new SocketException(Marshal.GetLastWin32Error());
            }
        }

19 Source : UnixApi.cs
with Apache License 2.0
from cdy816

internal static unsafe bool GetReusePort(IntPtr socket)
        {
            int value = 0;
            int status = 0;
            int optLen = sizeof(int);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                status = getsockopt(socket.ToInt32(), SOL_SOCKET_LINUX, SO_REUSEPORT_LINUX, (byte*)&value, &optLen);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                status = getsockopt(socket.ToInt32(), SOL_SOCKET_OSX, SO_REUSEPORT_OSX, (byte*)&value, &optLen);
            }
            if (status != 0)
            {
                throw new SocketException(Marshal.GetLastWin32Error());
            }
            return value != 0;
        }

19 Source : UnixApi.cs
with Apache License 2.0
from cdy816

internal static unsafe void SetReusePort(IntPtr socket, int value)
        {
            int status = 0;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                status = setsockopt(socket.ToInt32(), SOL_SOCKET_LINUX, SO_REUSEPORT_LINUX, (IntPtr)(&value), sizeof(int));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                status = setsockopt(socket.ToInt32(), SOL_SOCKET_OSX, SO_REUSEPORT_OSX, (IntPtr)(&value), sizeof(int));
            }
            if (status != 0)
            {
                throw new SocketException(Marshal.GetLastWin32Error());
            }
        }

19 Source : NativeMethods.cs
with MIT License
from CefNet

public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
		{
			if (IntPtr.Size == 8)
				return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
			else
				return new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong.ToInt32()));
		}

19 Source : ListViewEx.cs
with GNU General Public License v3.0
from Ch3shireDev

protected int[] GetColumnOrder()
        {
            var lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);

            var res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar);
            if (res.ToInt32() == 0)
            {
                Marshal.FreeHGlobal(lPar);
                return null;
            }

            var order = new int[Columns.Count];
            Marshal.Copy(lPar, order, 0, Columns.Count);

            Marshal.FreeHGlobal(lPar);

            return order;
        }

19 Source : NSubsysUtil.cs
with GNU General Public License v3.0
from chaincase-app

public static bool ProcessFile(string exeFilePath)
		{
			Console.WriteLine($"{nameof(NSubsys)}: Subsystem Changer for Windows PE files.");
			Console.WriteLine($"{nameof(NSubsys)}: Target EXE {exeFilePath}.");
			using var peFile = new PeUtility(exeFilePath);
			SubSystemType subsysVal;
			var subsysOffset = peFile.MainHeaderOffset;

			subsysVal = (SubSystemType)peFile.OptionalHeader.Subsystem;
			subsysOffset += Marshal.OffsetOf<ImageOptionalHeader>(nameof(ImageOptionalHeader.Subsystem)).ToInt32();

			switch (subsysVal)
			{
				case SubSystemType.ImageSubSystemWindowsGui:
					Console.WriteLine($"{nameof(NSubsys)}: Executable file is already a Win32 App!");
					return true;

				case SubSystemType.ImageSubSystemWindowsCui:
					Console.WriteLine($"{nameof(NSubsys)}: Console app detected...");
					Console.WriteLine($"{nameof(NSubsys)}: Converting...");

					var subsysSetting = BitConverter.GetBytes((ushort)SubSystemType.ImageSubSystemWindowsGui);

					if (!BitConverter.IsLittleEndian)
					{
						Array.Reverse(subsysSetting);
					}

					if (peFile.Stream.CanWrite)
					{
						peFile.Stream.Seek(subsysOffset, SeekOrigin.Begin);
						peFile.Stream.Write(subsysSetting, 0, subsysSetting.Length);
						Console.WriteLine($"{nameof(NSubsys)}: Conversion Complete...");
					}
					else
					{
						Console.WriteLine($"{nameof(NSubsys)}: Can't write changes!");
						Console.WriteLine($"{nameof(NSubsys)}: Conversion Failed...");
					}

					return true;

				default:
					Console.WriteLine($"{nameof(NSubsys)}: Unsupported subsystem number: {subsysVal}.");
					return false;
			}
		}

19 Source : Program.cs
with MIT License
from charanroaxz

static void Main(string[] args)
        {
            string version = "v2.0.4-beta";
            string d2rPath = "Game.exe";

            // NOTE: if you are going to copy & modify this then please atleast write my name correct!
            PrintASCIIArt(); // 'colored' logo
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"			                                       _____  _______ _______ _______ _     _ ____" +
                $"___  ______ \n {version.PadRight(16)}			                      |_____] |_____|    |    |       |_" +
                $"____| |______ |_____/ \n______________________________________________________________|  " +
                $"     |     |    |    |_____  |     | |______ |    \\_ \n");
            Console.ForegroundColor = ConsoleColor.Gray;

            // overwrite path if args are set
            if (args.Length > 0)
                d2rPath = args[0];

            if (!File.Exists(d2rPath))
            {
                ConsolePrint($"Error, {d2rPath} does not exist!", ConsoleColor.Red);
                ConsolePrint("Usage: D2ROffline.exe PATH_TO_GAMEDOTEXE", ConsoleColor.White);
                ConsolePrint("Press any key to exit...", ConsoleColor.Yellow);
                Console.ReadKey();
                return;
            }

            ConsolePrint("Launching game...");

            var pInfo = new ProcessStartInfo(d2rPath);

            //if (args.Length != 1)
            //    pInfo.Arguments = args[1];
            //else 
            //    ConsolePrint("Extra parameters not found. Proceeding...", ConsoleColor.DarkYellow);

            var d2r = Process.Start(pInfo);

            // wait for proc to properly enter userland to bypreplaced first few anti-cheating checks
            ConsolePrint("Process started...");

            IntPtr hProcess = OpenProcess(ProcessAccessFlags.PROCESS_ALL_ACCESS, false, d2r.Id);
            ConsolePrint("Opening process...");
            if (hProcess == IntPtr.Zero)
            {
                ConsolePrint("Failed on OpenProcess. Handle is invalid.", ConsoleColor.Red);
                ConsolePrint("Press any key to exit...", ConsoleColor.Yellow);
                Console.ReadKey();
                return;
            }

            // pre setup
            WaitForData(hProcess, d2r.MainModule.BaseAddress, 0x22D8858);
            Thread.Sleep(20); // NOTE: patch before this to get language working, may causes crash?

            // suspend process
            ConsolePrint("Suspending process...");
            NtSuspendProcess(hProcess);
            ConsolePrint("Process suspended");

            if (VirtualQueryEx(hProcess, d2r.MainModule.BaseAddress, out MEMORY_BASIC_INFORMATION basicInformation, Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) == 0)
            {
                ConsolePrint("Failed on VirtualQueryEx. Return is 0 bytes.", ConsoleColor.Red);
                ConsolePrint("Press any key to exit...", ConsoleColor.Yellow);
                Console.ReadKey();
                return;
            }
            IntPtr regionBase = basicInformation.baseAddress;
            IntPtr regionSize = basicInformation.regionSize;

            ConsolePrint("Remapping process..");
            IntPtr addr = RemapMemoryRegion(hProcess, regionBase, regionSize.ToInt32(), MemoryProtectionConstraints.PAGE_EXECUTE_READWRITE);

            ConsolePrint("Resuming process..");
            NtResumeProcess(hProcess);
            CloseHandle(hProcess);

            ConsolePrint("Done!", ConsoleColor.Green);
            ConsolePrint("Press any key to exit...", ConsoleColor.Yellow);
            Console.ReadKey();
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from Charltsing

protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x219)
            {
                Debug.WriteLine("WParam:{0} ,LParam:{1},Msg:{2},Result:{3}", m.WParam, m.LParam, m.Msg, m.Result);
                if (m.WParam.ToInt32() == 7)                                               //设备插入或拔出
                {
                    if (!HasAndroid)
                        DeviceTimer.Start();
                    else
                        Close();
                }
            }
            try
            {
                base.WndProc(ref m);
            }
            catch { }
        }

19 Source : Program.cs
with MIT License
from checkymander

private static IntPtr attachProcess()
        {
            Console.Clear();
            Process[] processes = Process.GetProcesses();
            var procName = "list";
            Console.WriteLine("Enter the ID of the process you want to impersonate.");
            procName = Console.ReadLine();
            Process targetProcess = null;
            try
            {
                targetProcess = Process.GetProcessById(int.Parse(procName));
                Console.WriteLine("Successfully Connected to process ID {0} - {1}", targetProcess.Id, targetProcess.ProcessName);
            }
            catch
            {
                Console.WriteLine("Failed to find process with ID: {0}", procName);
            }
            //Open a handle to the process
            IntPtr ptr = WindowsAPIHelper.OpenProcess(WindowsAPIHelper.ProcessAccessFlags.All, false, targetProcess.Id);
            if (ptr == IntPtr.Zero) { Console.WriteLine("OpenProcess Failed!"); } else { Console.WriteLine("OpenProcess Succeeded: " + ptr.ToInt32().ToString()); }
            return ptr;
        }

19 Source : about.cs
with BSD 2-Clause "Simplified" License
from chengse66

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
	{
		switch ((Keys)msg.WParam.ToInt32())
		{
			case Keys.Enter:

			case Keys.Escape: Close(); break;
		}

		return base.ProcessCmdKey(ref msg, keyData);
	}

19 Source : StaticCallbacks.cs
with MIT License
from chexiongsheng

[MonoPInvokeCallback(typeof(V8DestructorCallback))]
        internal static void GeneralDestructor(IntPtr self, long data)
        {
            try
            {
                int jsEnvIdx, callbackIdx;
                Utils.LongToTwoInt(data, out jsEnvIdx, out callbackIdx);
                JsEnv.jsEnvs[jsEnvIdx].JsReleaseObject(self.ToInt32());
            }
            catch {}
        }

See More Examples