System.Runtime.InteropServices.Marshal.SizeOf()

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

10202 Examples 7

19 Source : DMSkinComplexWindow.cs
with MIT License
from 944095635

void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            // MINMAXINFO structure  
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            // Get handle for nearest monitor to this window  
            IntPtr hMonitor = NativeMethods.MonitorFromWindow(Handle, NativeConstants.MONITOR_DEFAULTTONEAREST);

            // Get monitor info   显示屏
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            NativeMethods.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo);

            // Convert working area  
            RECT workingArea = monitorInfo.rcWork;

            // Set the maximized size of the window  
            //ptMaxSize:  设置窗口最大化时的宽度、高度
            //mmi.ptMaxSize.x = (int)dpiIndependentSize.X;
            //mmi.ptMaxSize.y = (int)dpiIndependentSize.Y;

            // Set the position of the maximized window  
            mmi.ptMaxPosition.x = workingArea.left;
            mmi.ptMaxPosition.y = workingArea.top;

            // Get HwndSource  
            HwndSource source = HwndSource.FromHwnd(Handle);
            if (source == null)
                // Should never be null  
                throw new Exception("Cannot get HwndSource instance.");
            if (source.CompositionTarget == null)
                // Should never be null  
                throw new Exception("Cannot get HwndTarget instance.");

            Matrix matrix = source.CompositionTarget.TransformToDevice;

            Point dpiIndenpendentTrackingSize = matrix.Transform(new Point(
               this.MinWidth,
               this.MinHeight
               ));

            //if (DMFullScreen)
            //{
            //    Point dpiSize = matrix.Transform(new Point(
            //  SystemParameters.PrimaryScreenWidth,
            //  SystemParameters.PrimaryScreenHeight
            //  ));

            //    mmi.ptMaxSize.x = (int)dpiSize.X;
            //    mmi.ptMaxSize.y = (int)dpiSize.Y;
            //}
            //else
            //{
            //    mmi.ptMaxSize.x = workingArea.right;
            //    mmi.ptMaxSize.y = workingArea.bottom;
            //}

            // Set the minimum tracking size ptMinTrackSize: 设置窗口最小宽度、高度 
            mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X;
            mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y;

            Marshal.StructureToPtr(mmi, lParam, true);
        }

19 Source : DMSkinSimpleWindow.cs
with MIT License
from 944095635

void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            // MINMAXINFO structure  
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            //拿到最靠近当前软件的显示器
            IntPtr hMonitor = NativeMethods.MonitorFromWindow(Handle, NativeConstants.MONITOR_DEFAULTTONEAREST);

            // Get monitor info   显示屏
            MONITORINFOEX monitorInfo = new MONITORINFOEX();

            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            NativeMethods.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo);

            // Convert working area  
            RECT workingArea = monitorInfo.rcWork;

            //设置最大化的时候的坐标 
            mmi.ptMaxPosition.x = workingArea.left;
            mmi.ptMaxPosition.y = workingArea.top;

            if (source == null)
                throw new Exception("Cannot get HwndSource instance.");
            if (source.CompositionTarget == null)
                throw new Exception("Cannot get HwndTarget instance.");

            Matrix matrix = source.CompositionTarget.TransformToDevice;

            Point dpiIndenpendentTrackingSize = matrix.Transform(new Point(
               this.MinWidth,
               this.MinHeight));

            if (DMFullScreen)
            {
                Point dpiSize = matrix.Transform(new Point(
              SystemParameters.PrimaryScreenWidth,
              SystemParameters.PrimaryScreenHeight
              ));

                mmi.ptMaxSize.x = (int)dpiSize.X;
                mmi.ptMaxSize.y = (int)dpiSize.Y;
            }
            else
            {
                //设置窗口最大化的尺寸
                mmi.ptMaxSize.x = workingArea.right - workingArea.left;
                mmi.ptMaxSize.y = workingArea.bottom;
            }

            //设置最小跟踪大小
            mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X;
            mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y;

            Marshal.StructureToPtr(mmi, lParam, true);
        }

19 Source : DellSmbiosBzh.cs
with GNU General Public License v3.0
from AaronKelley

public static uint? ExecuteCommand(SmbiosCommand command, uint argument = NoParameter)
        {
            if (!IsInitialized)
            {
                return null;
            }

            SmbiosPackage package = new SmbiosPackage
            {
                Command = (uint)command,
                Data = argument,
                Output1 = 0,
                Output2 = 0
            };

            uint resultSize = 0;

            bool status = ServiceMethods.DeviceIoControl(DriverHandle, IoctlCode, ref package, Marshal.SizeOf(package), ref package, Marshal.SizeOf(package), ref resultSize, IntPtr.Zero);

            if (status == false)
            {
                return null;
            }
            else
            {
                if (package.Command != uint.MaxValue)
                {
                    return package.Command;
                }
                else
                {
                    return null;
                }
            }
        }

19 Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley

private static byte[] StructToByteArray(SmiObject message)
        {
            int size = Marshal.SizeOf(message);
            byte[] array = new byte[size];

            IntPtr pointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(message, pointer, true);
            Marshal.Copy(pointer, array, 0, size);
            Marshal.FreeHGlobal(pointer);
            return array;
        }

19 Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley

private static SmiObject ByteArrayToStruct(byte[] array)
        {
            SmiObject message = new SmiObject();

            int size = Marshal.SizeOf(message);
            IntPtr pointer = Marshal.AllocHGlobal(size);

            Marshal.Copy(array, 0, pointer, size);

            message = (SmiObject)Marshal.PtrToStructure(pointer, message.GetType());
            Marshal.FreeHGlobal(pointer);

            return message;
        }

19 Source : WindowHooks.cs
with GNU General Public License v3.0
from Adam-Wilkinson

public static Rectangle CurrentMonitorSize()
        {
            NativeMethods.GetCursorPos(out POINT lpPoint);
            IntPtr lPrimaryScreen = NativeMethods.MonitorFromPoint(lpPoint, NativeMethods.MonitorOptions.MONITOR_DEFAULTTOPRIMARY);
            MONITORINFO lPrimaryScreenInfo = new();
            lPrimaryScreenInfo.cbSize = (uint)Marshal.SizeOf(lPrimaryScreenInfo);
            if (NativeMethods.GetMonitorInfo(lPrimaryScreen, lPrimaryScreenInfo) == false)
            {
                Debug.WriteLine(Marshal.GetLastWin32Error());
                return new Rectangle();
            }
            return new Rectangle { Rect = lPrimaryScreenInfo.rcWork };
        }

19 Source : WindowHooks.cs
with GNU General Public License v3.0
from Adam-Wilkinson

private static bool MonitorEnumCallBack(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData)
            {
                Debug.WriteLine(hMonitor);
                MONITORINFO mon_info = new();
                mon_info.cbSize = (uint)Marshal.SizeOf(mon_info);
                NativeMethods.GetMonitorInfo(hMonitor, mon_info);
                Debug.WriteLine(Marshal.GetLastWin32Error());
                AllMonitorInfo.Add(mon_info);
                return true;
            }

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

public static void RunWithTokenOf(
			int ProcessID,
			string ExeToRun,
			string Arguments,
			string WorkingDir = "")
		{
			try
			{
				#region Process ExeToRun, Arguments and WorkingDir

				// If ExeToRun is not absolute path, then let it be
				ExeToRun = Environment.ExpandEnvironmentVariables(ExeToRun);
				if (!ExeToRun.Contains("\\"))
				{
					foreach (string path in Environment.ExpandEnvironmentVariables("%path%").Split(';'))
					{
						string guess = path + "\\" + ExeToRun;
						if (File.Exists(guess)) { ExeToRun = guess; break; }
					}
				}
                if (!File.Exists(ExeToRun)) return;

				// If WorkingDir not exist, let it be the dir of ExeToRun
				// ExeToRun no dir? Impossible, as I would GoComplain() already
				WorkingDir = Environment.ExpandEnvironmentVariables(WorkingDir);
				if (!Directory.Exists(WorkingDir)) WorkingDir = Path.GetDirectoryName(ExeToRun);

				// If arguments exist, CmdLine must include ExeToRun as well
				Arguments = Environment.ExpandEnvironmentVariables(Arguments);
				string CmdLine = null;
				if (Arguments != "")
				{
					if (ExeToRun.Contains(" "))
						CmdLine = "\"" + ExeToRun + "\" " + Arguments;
					else
						CmdLine = ExeToRun + " " + Arguments;
				}

				#endregion

				// Set privileges of current process
				string privs = "SeDebugPrivilege";
				if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, out hToken))
                    return;

				foreach (string priv in privs.Split(','))
				{
                    if (!LookupPrivilegeValue("", priv, out LUID Luid))
                        return;

                    TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
					TP.PrivilegeCount = 1;
					TP.Luid = Luid;
					TP.Attrs = SE_PRIVILEGE_ENABLED;
                    if (!(AdjustTokenPrivileges(hToken, false, ref TP, 0, IntPtr.Zero, IntPtr.Zero) & Marshal.GetLastWin32Error() == 0))
                        return;
				}
				CloseHandle(hToken);

				// Open process by PID
				hProc = OpenProcess(ProcessAccessFlags.All, false, ProcessID);
                if (hProc == null) return;

                // Open process token
                if (!OpenProcessToken(hProc, TOKEN_DUPLICATE | TOKEN_QUERY, out hToken)) return;

                // Duplicate to hDupToken
                if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, ref dummySA,
                    SecurityImpersonationLevel.SecurityIdentification,
                    TokenType.TokenPrimary, out hDupToken))
                    return;

				// Set session ID to make sure it shows in current user desktop
				// Only possible when SuperCMD running as SYSTEM!
                if (ForceTokenUseActiveSessionID)
                {
                    uint SID = WTSGetActiveConsoleSessionId();
                    if (!SetTokenInformation(hDupToken, TOKEN_INFORMATION_CLreplaced_TokenSessionId, ref SID, (uint)sizeof(uint)))
                        return;
                }

				// Create environment block
				if (!CreateEnvironmentBlock(out pEnvBlock, hToken, true))
                    return;

				// Create process with the token we "stole" ^^
				uint dwCreationFlags = (NORMAL_PRIORITY_CLreplaced | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT);
				SI = new STARTUPINFO();
				SI.cb = Marshal.SizeOf(SI);
				SI.lpDesktop = "winsta0\\default";
				PI = new PROCESSINFO();

				// CreateProcessWithTokenW doesn't work in Safe Mode
				// CreateProcessAsUserW works, but if the Session ID is different,
				// we need to set it via SetTokenInformation()
				if (!CreateProcessWithTokenW(hDupToken, LogonFlags.WithProfile, ExeToRun, CmdLine,
					dwCreationFlags, pEnvBlock, WorkingDir, ref SI, out PI))
				{
					if (!CreateProcessAsUserW(hDupToken, ExeToRun, CmdLine, ref dummySA, ref dummySA,
						false, dwCreationFlags, pEnvBlock, WorkingDir, ref SI, out PI))
					{
                        return;
					}
				}
				CleanUp();
			}
			catch (Exception)
			{}
		}

19 Source : NotifyIcon.cs
with GNU General Public License v3.0
from aduskin

private bool FindNotifyIcon(IntPtr hTrayWnd, ref InteropValues.RECT rectNotify)
        {
            InteropMethods.GetWindowRect(hTrayWnd, out var rectTray);
            var count = (int)InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_BUTTONCOUNT, 0, IntPtr.Zero);

            var isFind = false;
            if (count > 0)
            {
                InteropMethods.GetWindowThreadProcessId(hTrayWnd, out var trayPid);
                var hProcess = InteropMethods.OpenProcess(InteropValues.ProcessAccess.VMOperation | InteropValues.ProcessAccess.VMRead | InteropValues.ProcessAccess.VMWrite, false, trayPid);
                var address = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, 1024, InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);

                var btnData = new InteropValues.TBBUTTON();
                var trayData = new InteropValues.TRAYDATA();
                var handel = Process.GetCurrentProcess().Id;

                for (uint i = 0; i < count; i++)
                {
                    InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GETBUTTON, i, address);
                    var isTrue = InteropMethods.ReadProcessMemory(hProcess, address, out btnData, Marshal.SizeOf(btnData), out _);
                    if (!isTrue) continue;
                    if (btnData.dwData == IntPtr.Zero)
                    {
                        btnData.dwData = btnData.iString;
                    }
                    InteropMethods.ReadProcessMemory(hProcess, btnData.dwData, out trayData, Marshal.SizeOf(trayData), out _);
                    InteropMethods.GetWindowThreadProcessId(trayData.hwnd, out var dwProcessId);
                    if (dwProcessId == (uint)handel)
                    {
                        var rect = new InteropValues.RECT();
                        var lngRect = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, Marshal.SizeOf(typeof(Rect)), InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);
                        InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GEreplacedEMRECT, i, lngRect);
                        InteropMethods.ReadProcessMemory(hProcess, lngRect, out rect, Marshal.SizeOf(rect), out _);

                        InteropMethods.VirtualFreeEx(hProcess, lngRect, Marshal.SizeOf(rect), InteropValues.FreeType.Decommit);
                        InteropMethods.VirtualFreeEx(hProcess, lngRect, 0, InteropValues.FreeType.Release);

                        var left = rectTray.Left + rect.Left;
                        var top = rectTray.Top + rect.Top;
                        var botton = rectTray.Top + rect.Bottom;
                        var right = rectTray.Left + rect.Right;
                        rectNotify = new InteropValues.RECT
                        {
                            Left = left,
                            Right = right,
                            Top = top,
                            Bottom = botton
                        };
                        isFind = true;
                        break;
                    }
                }
                InteropMethods.VirtualFreeEx(hProcess, address, 0x4096, InteropValues.FreeType.Decommit);
                InteropMethods.VirtualFreeEx(hProcess, address, 0, InteropValues.FreeType.Release);
                InteropMethods.CloseHandle(hProcess);
            }
            return isFind;            
        }

19 Source : Unicorn.cs
with MIT License
from AeonLucid

public IEnumerable<UcMemRegion> MemRegions()
        {
            var err = UcNative.UcMemRegions(Handle, out var regions, out var count);
            if (err != UcErr.UC_ERR_OK)
            {
                throw new UcException(err);
            }

            var size = Marshal.SizeOf<UcMemRegion>();
            var result = new UcMemRegion[count];

            for (var i = 0; i < count; i++)
            {
                yield return Marshal.PtrToStructure<UcMemRegion>(regions + (i * size));
            }
        }

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

public static ProcessModuleWow64Safe[] ModulesWow64Safe(this Process p)
        {
            if (ModuleCache.Count > 100)
                ModuleCache.Clear();

            const int LIST_MODULES_ALL = 3;
            const int MAX_PATH = 260;

            var hModules = new IntPtr[1024];

            uint cb = (uint)IntPtr.Size*(uint)hModules.Length;
            uint cbNeeded;

            if (!WinAPI.EnumProcessModulesEx(p.Handle, hModules, cb, out cbNeeded, LIST_MODULES_ALL))
                throw new Win32Exception();
            uint numMods = cbNeeded / (uint)IntPtr.Size;

            int hash = p.StartTime.GetHashCode() + p.Id + (int)numMods;
            if (ModuleCache.ContainsKey(hash))
                return ModuleCache[hash];

            var ret = new List<ProcessModuleWow64Safe>();

            // everything below is fairly expensive, which is why we cache!
            var sb = new StringBuilder(MAX_PATH);
            for (int i = 0; i < numMods; i++)
            {
                sb.Clear();
                if (WinAPI.GetModuleFileNameEx(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    throw new Win32Exception();
                string fileName = sb.ToString();

                sb.Clear();
                if (WinAPI.GetModuleBaseName(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    throw new Win32Exception();
                string baseName = sb.ToString();

                var moduleInfo = new WinAPI.MODULEINFO();
                if (!WinAPI.GetModuleInformation(p.Handle, hModules[i], out moduleInfo, (uint)Marshal.SizeOf(moduleInfo)))
                    throw new Win32Exception();

                ret.Add(new ProcessModuleWow64Safe()
                {
                    FileName = fileName,
                    BaseAddress = moduleInfo.lpBaseOfDll,
                    ModuleMemorySize = (int)moduleInfo.SizeOfImage,
                    EntryPointAddress = moduleInfo.EntryPoint,
                    ModuleName = baseName
                });
            }

            ModuleCache.Add(hash, ret.ToArray());

            return ret.ToArray();
        }

19 Source : WaveOut.cs
with GNU General Public License v3.0
from ahmed605

public bool Play()
        {
            lock(this)
            {
                m_PlayEvent.Reset();
                m_Playing = WaveNative.waveOutWrite(m_WaveOut, ref m_Header, Marshal.SizeOf(m_Header)) == WaveNative.MMSYSERR_NOERROR;
                return m_Playing;
            }
        }

19 Source : WaveOut.cs
with GNU General Public License v3.0
from ahmed605

public void Dispose()
        {
            if (m_Header.lpData != IntPtr.Zero)
            {
                WaveNative.waveOutUnprepareHeader(m_WaveOut, ref m_Header, Marshal.SizeOf(m_Header));
                m_HeaderHandle.Free();
                m_Header.lpData = IntPtr.Zero;
            }
            m_PlayEvent.Close();
            if (m_HeaderDataHandle.IsAllocated)
                m_HeaderDataHandle.Free();
            GC.SuppressFinalize(this);
        }

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

private void RegisterRawInput(IntPtr hWnd)
		{
			// if create RegisterRawInput fail, exit process to try again.
			try
			{
				RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[]
				{
					new RAWINPUTDEVICE(){
						usUsagePage = util.HID_USAGEPAGE_GENERIC,
						usUsage = util.HID_USAGE_KEYBOARD,
						dwFlags = (int)RawInputDeviceFlags.InputSink,
						hwndTarget = hWnd
					},
#if !DEBUG
					new RAWINPUTDEVICE(){
					    usUsagePage = util.HID_USAGEPAGE_GENERIC,
					    usUsage = util.HID_USAGE_MOUSE,				    
					    dwFlags = (int)RawInputDeviceFlags.InputSink,
					    hwndTarget = hWnd
					},
#endif
				};
				bool succeed = user32.RegisterRawInputDevices(rid, rid.Length, Marshal.SizeOf(rid[0]));
				TraceLogger.Instance.WriteLineInfo("RegisterRawInputDevices : " + succeed);
				if (!succeed)
					throw new Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
			}
			catch (Exception ex)
			{
				TraceLogger.Instance.WriteException(ex);
				Application.Exit();
			}
		}

19 Source : SteamVR_TrackedCamera.cs
with MIT License
from ajayyy

void Update()
		{
			if (Time.frameCount == prevFrameCount)
				return;

			prevFrameCount = Time.frameCount;

			if (videostream.handle == 0)
				return;

			var vr = SteamVR.instance;
			if (vr == null)
				return;

			var trackedCamera = OpenVR.TrackedCamera;
			if (trackedCamera == null)
				return;

			var nativeTex = System.IntPtr.Zero;
			var deviceTexture = (_texture != null) ? _texture : new Texture2D(2, 2);
			var headerSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(header.GetType());

			if (vr.textureType == ETextureType.OpenGL)
			{
				if (glTextureId != 0)
					trackedCamera.ReleaseVideoStreamTextureGL(videostream.handle, glTextureId);

				if (trackedCamera.GetVideoStreamTextureGL(videostream.handle, frameType, ref glTextureId, ref header, headerSize) != EVRTrackedCameraError.None)
					return;

				nativeTex = (System.IntPtr)glTextureId;
            }
			else if (vr.textureType == ETextureType.DirectX)
			{
				if (trackedCamera.GetVideoStreamTextureD3D11(videostream.handle, frameType, deviceTexture.GetNativeTexturePtr(), ref nativeTex, ref header, headerSize) != EVRTrackedCameraError.None)
					return;
			}

			if (_texture == null)
			{
				_texture = Texture2D.CreateExternalTexture((int)header.nWidth, (int)header.nHeight, TextureFormat.RGBA32, false, false, nativeTex);

				uint width = 0, height = 0;
				var frameBounds = new VRTextureBounds_t();
				if (trackedCamera.GetVideoStreamTextureSize(deviceIndex, frameType, ref frameBounds, ref width, ref height) == EVRTrackedCameraError.None)
				{
					// Account for textures being upside-down in Unity.
					frameBounds.vMin = 1.0f - frameBounds.vMin;
					frameBounds.vMax = 1.0f - frameBounds.vMax;
					this.frameBounds = frameBounds;
				}
			}
			else
			{
				_texture.UpdateExternalTexture(nativeTex);
			}
		}

19 Source : MemoryManager.cs
with MIT License
from Akaion

internal MemoryBasicInformation QueryVirtualMemory(IntPtr baseAddress)
        {
            if (!VirtualQueryEx(_processHandle, baseAddress, out var memoryBasicInformation, Marshal.SizeOf<MemoryBasicInformation>()))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to query a region of virtual memory in the remote process");
            }
            
            return memoryBasicInformation;
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

internal TStructure ReadVirtualMemory<TStructure>(IntPtr baseAddress) where TStructure : struct
        {
            var structureSize = Marshal.SizeOf<TStructure>();
            
            var structureBuffer = Marshal.AllocHGlobal(structureSize);

            if (!ReadProcessMemory(_processHandle, baseAddress, structureBuffer, structureSize, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
            }

            try
            {
                return Marshal.PtrToStructure<TStructure>(structureBuffer);
            }

            finally
            {
                Marshal.FreeHGlobal(structureBuffer);
            }
        }

19 Source : MemoryManager.cs
with MIT License
from Akaion

internal void WriteVirtualMemory<TStructure>(IntPtr baseAddress, TStructure structureToWrite) where TStructure : struct
        {
            var structureSize = Marshal.SizeOf<TStructure>();
            
            // Adjust the protection of the virtual memory region to ensure it has write privileges
            
            var originalProtectionType = ProtectVirtualMemory(baseAddress, structureSize, MemoryProtection.ReadWrite);

            var structureToWriteBufferHandle = GCHandle.Alloc(structureToWrite, GCHandleType.Pinned);
            
            if (!WriteProcessMemory(_processHandle, baseAddress, structureToWriteBufferHandle.AddrOfPinnedObject(), structureSize, IntPtr.Zero))
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write into a region of virtual memory in the remote process");
            }
            
            // Restore the original protection of the virtual memory region
            
            ProtectVirtualMemory(baseAddress, structureSize, originalProtectionType);

            structureToWriteBufferHandle.Free();
        }

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 : SystemMenu.cs
with MIT License
from AlexanderPro

public void SetMenuItemText(int id, string text)
        {
            var info = new MenuItemInfo();
            info.cbSize = (uint)Marshal.SizeOf(info);
            info.fMask = NativeConstants.MIIM_TYPE;
            info.fType = NativeConstants.MFT_STRING;
            info.dwTypeData = text;
            info.cch = (uint)text.Length;
            var windowMenuHandle = NativeMethods.GetSystemMenu(WindowHandle, false);
            NativeMethods.SetMenuItemInfo(windowMenuHandle, id, false, ref info);
        }

19 Source : Window.cs
with MIT License
from AlexanderPro

public void AeroGlreplacedForEightAndHigher(bool enable)
        {
            var accent = new AccentPolicy();
            var accentStructSize = Marshal.SizeOf(accent);
            accent.AccentState = enable ? AccentState.ACCENT_ENABLE_BLURBEHIND : AccentState.ACCENT_DISABLED;
            var accentPtr = Marshal.AllocHGlobal(accentStructSize);
            try
            {
                Marshal.StructureToPtr(accent, accentPtr, false);
                var data = new WindowCompositionAttributeData();
                data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
                data.SizeOfData = accentStructSize;
                data.Data = accentPtr;
                NativeMethods.SetWindowCompositionAttribute(Handle, ref data);
            }
            finally
            {
                Marshal.FreeHGlobal(accentPtr);
            }
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

private static WINDOWPLACEMENT GetWindowPlacement(IntPtr hWnd)
        {
            var placement = new WINDOWPLACEMENT();
            placement.length = Marshal.SizeOf(placement);
            NativeMethods.GetWindowPlacement(hWnd, ref placement);
            return placement;
        }

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 : SystemUtils.cs
with MIT License
from AlexanderPro

public static string GetTotalMemory()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return $"{info.PhysicalTotal.ToInt64() >> 8} MB";
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static string GetAvailableMemory()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return $"{info.PhysicalAvailable.ToInt64() >> 8} MB";
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static string GetCommits()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return $"{info.CommitTotal.ToInt64() >> 8} MB / {info.CommitLimit.ToInt64() >> 8} MB";
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static uint GetNumberProcesses()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return info.ProcessCount;
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static uint GetNumberThreads()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return info.ThreadCount;
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static uint GetNumberHandles()
        {
            var info = new PerformanceInformation
            {
                cb = Marshal.SizeOf<PerformanceInformation>()
            };
            GetPerformanceInfo(ref info, Marshal.SizeOf<PerformanceInformation>());
            return info.HandleCount;
        }

19 Source : Window.cs
with MIT License
from AlexanderPro

public WindowInfo GetWindowInfo()
        {
            var process = Process;
            var info = new WindowInfo();
            info.GetWindowText = GetWindowText();
            info.WM_GETTEXT = GetWmGettext();
            info.GetClreplacedName = GetClreplacedName();
            info.RealGetWindowClreplaced = RealGetWindowClreplaced();
            info.Handle = Handle;
            info.ParentHandle = NativeMethods.GetParent(Handle);
            info.Size = Size;
            info.ClientSize = ClientSize;
            info.FrameBounds = GetSystemMargins();
            info.ProcessId = ProcessId;
            info.ThreadId = WindowUtils.GetThreadId(Handle);
            info.GWL_STYLE = NativeMethods.GetWindowLong(Handle, NativeConstants.GWL_STYLE);
            info.GWL_EXSTYLE = NativeMethods.GetWindowLong(Handle, NativeConstants.GWL_EXSTYLE);
            info.GWL_ID = NativeMethods.GetWindowLong(Handle, NativeConstants.GWL_ID);
            info.GWL_USERDATA = NativeMethods.GetWindowLong(Handle, NativeConstants.GWL_USERDATA);
            info.GCL_STYLE = NativeMethods.GetClreplacedLong(Handle, NativeConstants.GCL_STYLE);
            info.GCL_WNDPROC = NativeMethods.GetClreplacedLong(Handle, NativeConstants.GCL_WNDPROC);
            info.DWL_DLGPROC = NativeMethods.GetClreplacedLong(Handle, NativeConstants.DWL_DLGPROC);
            info.DWL_USER = NativeMethods.GetClreplacedLong(Handle, NativeConstants.DWL_USER);
            info.FullPath = process == null ? "" : process.GetMainModuleFileName();
            info.FullPath = info.FullPath == null ? "" : info.FullPath;
            info.Priority = ProcessPriority;
            info.StartTime = process == null ? (DateTime?)null : process.StartTime;

            try
            {
                var processInfo = SystemUtils.GetWmiProcessInfo(process.Id);
                info.Owner = processInfo.Owner;
                info.CommandLine = processInfo.CommandLine;
                info.ThreadCount = processInfo.ThreadCount;
                info.HandleCount = processInfo.HandleCount;
                info.VirtualSize = processInfo.VirtualSize;
                info.WorkingSetSize = processInfo.WorkingSetSize;
            }
            catch
            {
            }

            try
            {
                info.FontName = GetFontName();
            }
            catch
            {
            }

            try
            {
                var windowInfo = new WINDOW_INFO();
                windowInfo.cbSize = Marshal.SizeOf(windowInfo);
                if (NativeMethods.GetWindowInfo(Handle, ref windowInfo))
                {
                    info.WindowInfoExStyle = windowInfo.dwExStyle;
                }
            }
            catch
            {
            }

            try
            {
                uint key;
                Byte alpha;
                uint flags;
                var result = NativeMethods.GetLayeredWindowAttributes(Handle, out key, out alpha, out flags);
                var layeredWindow = (LayeredWindow)flags;
                info.LWA_ALPHA = layeredWindow.HasFlag(LayeredWindow.LWA_ALPHA);
                info.LWA_COLORKEY = layeredWindow.HasFlag(LayeredWindow.LWA_COLORKEY);
            }
            catch
            {
            }

            try
            {
                info.Instance = process == null ? IntPtr.Zero : process.Modules[0].BaseAddress;
            }
            catch
            {
            }

            try
            {
                info.Parent = Path.GetFileName(process.GetParentProcess().MainModule.FileName);
            }
            catch
            {
            }

            try
            {
                var fileVersionInfo = process.MainModule.FileVersionInfo;
                info.ProductName = fileVersionInfo.ProductName;
                info.ProductVersion = fileVersionInfo.ProductVersion;
                info.FileVersion = fileVersionInfo.FileVersion;
                info.Copyright = fileVersionInfo.LegalCopyright;
            }
            catch
            {
            }

            /*try
            {
                var control = Control.FromHandle(Handle);
                var accessibilityObject = control.AccessibilityObject;
                info.AccessibleName = accessibilityObject == null ? "" : accessibilityObject.Name;
                info.AccessibleValue = accessibilityObject == null ? "" : accessibilityObject.Value;
                info.AccessibleRole = accessibilityObject == null ? "" : accessibilityObject.Role.ToString();
                info.AccessibleDescription = accessibilityObject == null ? "" : accessibilityObject.Description;
            }
            catch
            {
            }*/

            return info;
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

public static WindowInformation GetWindowInformation(IntPtr hWnd)
        {
            var text = GetWindowText(hWnd);
            var wmText = GetWmGettext(hWnd);
            var clreplacedName = GetClreplacedName(hWnd);
            var realWindowClreplaced = RealGetWindowClreplaced(hWnd);
            var hWndParent = NativeMethods.GetParent(hWnd);
            var size = GetWindowSize(hWnd);
            var clientSize = GetWindowClientSize(hWnd);
            var isVisible = NativeMethods.IsWindowVisible(hWnd);
            var placement = GetWindowPlacement(hWnd);
            var threadId = NativeMethods.GetWindowThreadProcessId(hWnd, out var processId);
            var process = GetProcessByIdSafely(processId);

            var gwlStyle = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_STYLE);
            var gwlExstyle = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_EXSTYLE);
            var gwlUserData = NativeMethods.GetWindowLong(hWnd, NativeConstants.GWL_USERDATA);
            var gclStyle = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.GCL_STYLE);
            var gclWndproc = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.GCL_WNDPROC);
            var dwlDlgproc = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.DWL_DLGPROC);
            var dwlUser = NativeMethods.GetClreplacedLong(hWnd, NativeConstants.DWL_USER);

            var windowDetailes = new Dictionary<string, string>();
            windowDetailes.Add("GetWindowText", text);
            windowDetailes.Add("WM_GETTEXT", wmText);
            windowDetailes.Add("GetClreplacedName", clreplacedName);
            windowDetailes.Add("RealGetClreplacedName", realWindowClreplaced);
            try
            {
                windowDetailes.Add("Font Name", GetFontName(hWnd));
            }
            catch
            {
            }

            windowDetailes.Add("Window Handle", $"0x{hWnd.ToInt64():X}");
            windowDetailes.Add("Parent Window Handle", hWndParent == IntPtr.Zero ? "-" : $"0x{hWndParent.ToInt64():X}");
            windowDetailes.Add("Is Window Visible", isVisible.ToString());
            windowDetailes.Add("Window Placement (showCmd)", placement.showCmd.ToString());
            windowDetailes.Add("Window Size", $"{size.Width}x{size.Height}");
            windowDetailes.Add("Window Client Size", $"{clientSize.Width}x{clientSize.Height}");

            try
            {
                var bounds = GetFrameBounds(hWnd);
                windowDetailes.Add("Window Extended Frame Bounds", $"{bounds.Top} {bounds.Right} {bounds.Bottom} {bounds.Left}");
            }
            catch
            {
            }

            try
            {
                windowDetailes.Add("Instance", $"0x{process.Modules[0].BaseAddress.ToInt64():X}");
            }
            catch
            {
            }
            
            windowDetailes.Add("GCL_WNDPROC", $"0x{gclWndproc:X}");
            windowDetailes.Add("DWL_DLGPROC", $"0x{dwlDlgproc:X}");
            windowDetailes.Add("GWL_STYLE", $"0x{gwlStyle:X}");
            windowDetailes.Add("GCL_STYLE", $"0x{gclStyle:X}");
            windowDetailes.Add("GWL_EXSTYLE", $"0x{gwlExstyle:X}");
            
            try
            {
                var windowInfo = new WINDOW_INFO();
                windowInfo.cbSize = Marshal.SizeOf(windowInfo);
                if (NativeMethods.GetWindowInfo(hWnd, ref windowInfo))
                {
                    windowDetailes.Add("WindowInfo.ExStyle", $"0x{windowInfo.dwExStyle:X}");
                }
            }
            catch
            {
            }
            
            try
            {
                uint key;
                Byte alpha;
                uint flags;
                var result = NativeMethods.GetLayeredWindowAttributes(hWnd, out key, out alpha, out flags);
                var layeredWindow = (LayeredWindow)flags;
                windowDetailes.Add("LWA_ALPHA", layeredWindow.HasFlag(LayeredWindow.LWA_ALPHA) ? "+" : "-");
                windowDetailes.Add("LWA_COLORKEY", layeredWindow.HasFlag(LayeredWindow.LWA_COLORKEY) ? "+" : "-");
            }
            catch
            {
            }
            
            windowDetailes.Add("GWL_USERDATA", $"0x{gwlUserData:X}");
            windowDetailes.Add("DWL_USER", $"0x{dwlUser:X}");

            var processDetailes = new Dictionary<string, string>();
            try
            {
                try
                {
                    processDetailes.Add("Full Path", process.MainModule.FileName);
                }
                catch
                {
                    var fileNameBuilder = new StringBuilder(1024);
                    var bufferLength = (uint)fileNameBuilder.Capacity + 1;
                    var fullPath = NativeMethods.QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, ref bufferLength) ? fileNameBuilder.ToString() : "";
                    processDetailes.Add("Full Path", fullPath);
                }
            }
            catch
            {
            }

            var processInfo = (WmiProcessInfo)null;
            try
            {
                processInfo = GetWmiProcessInfo(processId);
                processDetailes.Add("Command Line", processInfo.CommandLine);
            }
            catch
            {
            }

            try
            {
                processDetailes.Add("Started at", $"{process.StartTime:dd.MM.yyyy HH:mm:ss}");
            }
            catch
            {
            }

            try
            {
                processDetailes.Add("Owner", processInfo.Owner);
            }
            catch
            {
            }

            processDetailes.Add("Process Id", processId.ToString());
            try
            {
                var parentProcess = process.GetParentProcess();
                processDetailes.Add("Parent Process Id", parentProcess.Id.ToString());
                processDetailes.Add("Parent", Path.GetFileName(parentProcess.MainModule.FileName));
            }
            catch
            {
            }
            
            processDetailes.Add("Thread Id", threadId.ToString());

            try
            {
                processDetailes.Add("Priority", process.GetProcessPriority().ToString());
            }
            catch
            {
            }

            
            try
            {
                processDetailes.Add("Threads", processInfo.ThreadCount.ToString());
                processDetailes.Add("Handles", processInfo.HandleCount.ToString());
                processDetailes.Add("Working Set Size", processInfo.WorkingSetSize.ToString());
                processDetailes.Add("Virtual Size", processInfo.VirtualSize.ToString());
            }
            catch
            {
            }
            
            try
            {
                var fileVersionInfo = process.MainModule.FileVersionInfo;
                processDetailes.Add("Product Name", fileVersionInfo.ProductName);
                processDetailes.Add("Copyright", fileVersionInfo.LegalCopyright);
                processDetailes.Add("File Version", fileVersionInfo.FileVersion);
                processDetailes.Add("Product Version", fileVersionInfo.ProductVersion);
            }
            catch
            {
            }

            return new WindowInformation(windowDetailes, processDetailes);
        }

19 Source : Plugin.cs
with MIT License
from AlexanderPro

public void ListSetDefaultParams(int interfaceVersionLow, int interfaceVersionHigh, string iniFile)
        {
            var function = (ListSetDefaultParamsDelegate)LoadFunction<ListSetDefaultParamsDelegate>("ListSetDefaultParams");
            var defaultParams = new ListDefaultParamStruct();
            defaultParams.interfaceVersionLow = interfaceVersionLow;
            defaultParams.interfaceVersionHigh = interfaceVersionHigh;
            defaultParams.defaultIniFile = iniFile;
            defaultParams.size = Marshal.SizeOf(defaultParams);
            function(defaultParams);
        }

19 Source : ObjectToByte.cs
with MIT License
from allartprotocol

public static CompiledInstruction fromBytes(byte[] arr)
        {
            CompiledInstruction str = new CompiledInstruction();

            int size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, 0, ptr, size);

            str = (CompiledInstruction)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return str;
        }

19 Source : ObjectToByte.cs
with MIT License
from allartprotocol

public static byte[] getBytes(CompiledInstruction str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }

19 Source : UnsafeBlitFormatter.cs
with Apache License 2.0
from allenai

public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteNil();
                return;
            }

            var byteLen = value.Length * Marshal.SizeOf<T>();

            writer.WriteExtensionFormatHeader(new ExtensionHeader(this.TypeCode, byteLen));
            writer.Write(byteLen); // write original header(not array header)
            writer.Write(BitConverter.IsLittleEndian);
            writer.WriteRaw(MemoryMarshal.Cast<T, byte>(value));
        }

19 Source : UnsafeBlitFormatter.cs
with Apache License 2.0
from allenai

public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            if (reader.TryReadNil())
            {
                return null;
            }

            ExtensionHeader header = reader.ReadExtensionFormatHeader();
            if (header.TypeCode != this.TypeCode)
            {
                throw new InvalidOperationException("Invalid typeCode.");
            }

            var byteLength = reader.ReadInt32();
            var isLittleEndian = reader.ReadBoolean();

            // Allocate a T[] that we will return. We'll then cast the T[] as byte[] so we can copy the byte sequence directly into it.
            var result = new T[byteLength / Marshal.SizeOf<T>()];
            Span<byte> resultAsBytes = MemoryMarshal.Cast<T, byte>(result);
            reader.ReadRaw(byteLength).CopyTo(resultAsBytes);

            // Reverse the byte order if necessary.
            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                for (int i = 0, j = resultAsBytes.Length - 1; i < j; i++, j--)
                {
                    byte tmp = resultAsBytes[i];
                    resultAsBytes[i] = resultAsBytes[j];
                    resultAsBytes[j] = tmp;
                }
            }

            return result;
        }

19 Source : ArrayHelper.cs
with MIT License
from AlternateLife

internal static List<T> ConvertFromIntPtr<T>(IntPtr arrayPointer, ulong size, Func<IntPtr, T> creator)
        {
            var elements = new List<T>();
            var pointerSize = Marshal.SizeOf<IntPtr>();

            for (var i = 0; i < (int) size; i++)
            {
                var targetPointer = Marshal.ReadIntPtr(arrayPointer + pointerSize * i);

                elements.Add(creator(targetPointer));
            }

            return elements;
        }

19 Source : TextureHelpers.cs
with MIT License
from altimesh

public static unsafe cudaTextureDesc CreateCudaTextureDesc()
        {
            cudaTextureDesc texDesc;
            memset((byte*)&texDesc, Marshal.SizeOf(texDesc), 0);
            texDesc.addressMode[0] = (int)cudaTextureAddressMode.cudaAddressModeWrap;
            texDesc.addressMode[1] = (int)cudaTextureAddressMode.cudaAddressModeWrap;
            texDesc.filterMode = cudaTextureFilterMode.cudaFilterModePoint;
            texDesc.readMode = cudaTextureReadMode.cudaReadModeElementType;
            texDesc.normalizedCoords = 0;
            return texDesc;
        }

19 Source : TextureHelper.cs
with MIT License
from altimesh

public static unsafe cudaResourceDesc CreateCudaResourceDesc(cudaArray_t cuArrayTex)
        {
            cudaResourceDesc resDescTex;
            memset((byte*)&resDescTex, Marshal.SizeOf(resDescTex), 0);
            resDescTex.arrayStruct = cuArrayTex;
            resDescTex.resType = cudaResourceType.cudaResourceTypeArray;
            return resDescTex;
        }

19 Source : Utils.cs
with MIT License
from altskop

public static int SizeOf<T>()
        {
            var size = Marshal.SizeOf(typeof(T));
            return size;
        }

19 Source : MemoryUtil.cs
with GNU General Public License v3.0
from am0nsec

protected T GetStructureFromBlob<T>(Int64 offset) where T : struct {
            Span<byte> bytes = this.GetStructureBytesFromOffset<T>(offset);
            if (Marshal.SizeOf<T>() != bytes.Length)
                return default;

            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
            Marshal.Copy(bytes.ToArray(), 0, ptr, bytes.Length);
            T s = Marshal.PtrToStructure<T>(ptr);

            Marshal.FreeHGlobal(ptr);
            return s;
        }

19 Source : MemoryUtil.cs
with GNU General Public License v3.0
from am0nsec

protected Span<byte> GetStructureBytesFromOffset<T>(Int64 offset) where T : struct {
            Span<byte> s = stackalloc byte[Marshal.SizeOf<T>()];
            this.ModuleStream.Seek(offset, SeekOrigin.Begin);
            this.ModuleStream.Read(s);
            return s.ToArray();
        }

19 Source : SystemModule.cs
with GNU General Public License v3.0
from am0nsec

private Int64 GetModuleSectionOffset(Int16 cx)
            => this.ModuleDOSHeader.e_lfanew
            + Marshal.SizeOf<Structures.IMAGE_FILE_HEADER>()
            + this.ModuleNTHeaders.FileHeader.SizeOfOptionalHeader
            + sizeof(Int32) // sizeof(DWORD)
            + (Marshal.SizeOf<Structures.IMAGE_SECTION_HEADER>() * cx);

19 Source : IDWriteGdiInterop.cs
with MIT License
from amerkoleci

public unsafe IDWriteFont CreateFontFromLOGFONT(LogFont logFont)
        {
            int sizeOfLogFont = Marshal.SizeOf(logFont);
            byte* nativeLogFont = stackalloc byte[sizeOfLogFont];
            Marshal.StructureToPtr(logFont, new IntPtr(nativeLogFont), false);
            return CreateFontFromLOGFONT(new IntPtr(nativeLogFont));
        }

19 Source : IDWriteGdiInterop1.cs
with MIT License
from amerkoleci

public unsafe IDWriteFontSet GetMatchingFontsByLOGFONT(LogFont logFont, IDWriteFontSet fontSet)
        {
            int sizeOfLogFont = Marshal.SizeOf(logFont);
            byte* nativeLogFont = stackalloc byte[sizeOfLogFont];
            Marshal.StructureToPtr(logFont, new IntPtr(nativeLogFont), false);
            return GetMatchingFontsByLOGFONT(new IntPtr(nativeLogFont), fontSet);
        }

19 Source : PropertyAccessor.cs
with MIT License
from amerkoleci

internal unsafe void InitHeader<T>(ref PropertyHeader header) where T : struct
        {
            header.Size = Marshal.SizeOf<T>();
            header.HeaderSize = sizeof(PropertyHeader);
            header.Type = PropertyType;
            header.Obj = ObjectCode;
        }

19 Source : Includer.cs
with MIT License
from amerkoleci

private static unsafe nint shaderc_include_resolve(void* user_data, [MarshalAs(UnmanagedType.LPStr)] string requested_source, int type, [MarshalAs(UnmanagedType.LPStr)] string requesting_source, UIntPtr include_depth)
        {
            GCHandle gch = GCHandle.FromIntPtr((IntPtr)user_data);
#pragma warning disable CS8600
            Includer includer = (Includer)gch.Target;
#pragma warning restore CS8600

#pragma warning disable CS8602
            if (!includer._shadercIncludeResults.TryGetValue(requested_source, out IntPtr includeResultPtr))
#pragma warning restore CS8602
            {
                Native.shaderc_include_result includeResult = new();
                string path = requested_source;
                if (!Path.IsPathRooted(path))
                {
                    string rootPath = includer.RootPath;
                    if (includer._sourceToPath.ContainsKey(requesting_source)) {
                        rootPath = Path.GetDirectoryName(includer._sourceToPath[requesting_source]);
                    }
                    path = Path.Combine(rootPath, path);
                }
                includeResult.content = File.ReadAllText(path);
                includeResult.content_length = (UIntPtr)includeResult.content.Length;
                includeResult.source_name = requested_source;
                includeResult.source_name_length = (UIntPtr)includeResult.source_name.Length;

                includeResultPtr = Marshal.AllocHGlobal(Marshal.SizeOf(includeResult));
                Marshal.StructureToPtr(includeResult, includeResultPtr, false);
                includer._shadercIncludeResults.Add(requested_source, includeResultPtr);
                includer._ptrToName.Add(includeResultPtr, requested_source);
                includer._sourceToPath.Add(requested_source, path);
            }
            return includeResultPtr;
        }

19 Source : IDWriteGdiInterop1.cs
with MIT License
from amerkoleci

public unsafe IDWriteFont CreateFontFromLOGFONT(LogFont logFont, IDWriteFontCollection fontCollection)
        {
            int sizeOfLogFont = Marshal.SizeOf(logFont);
            byte* nativeLogFont = stackalloc byte[sizeOfLogFont];
            Marshal.StructureToPtr(logFont, new IntPtr(nativeLogFont), false);
            return CreateFontFromLOGFONT(new IntPtr(nativeLogFont), fontCollection);
        }

19 Source : CustomEffectFactory.cs
with MIT License
from amerkoleci

private int GetterImpl(IntPtr thisPtr, IntPtr dataPtr, int datasize, out int actualSize)
            {
                actualSize = Marshal.SizeOf<U>();
                if (dataPtr == IntPtr.Zero)
                    return Result.Ok.Code;

                var shadow = ToShadow(thisPtr);
                var callback = (ID2D1EffectImpl)shadow.Callback;

                var value = (U)PropertyInfo.GetValue(callback);
                Marshal.StructureToPtr(value, dataPtr, true);

                return Result.Ok.Code;
            }

19 Source : FluentAvaloniaTheme.cs
with MIT License
from amwx

private string GetTheme()
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && DefaultToUserTheme)
			{
				Win32Interop.OSVERSIONINFOEX osInfo = new Win32Interop.OSVERSIONINFOEX { OSVersionInfoSize = Marshal.SizeOf(typeof(Win32Interop.OSVERSIONINFOEX)) };
				Win32Interop.RtlGetVersion(ref osInfo);

                try
                {
                    var hc = new Win32Interop.HIGHCONTRAST
                    {
                        cbSize = (uint)Marshal.SizeOf<Win32Interop.HIGHCONTRAST>()
                    };

                    bool ok = Win32Interop.SystemParametersInfo(0x0042 /*SPI_GETHIGHCONTRAST*/, 0, ref hc, 0);

                    if (ok && (hc.dwFlags & HCF.HCF_HIGHCONTRASTON) == HCF.HCF_HIGHCONTRASTON)
                    {
                        _mode = HighContrastModeString;
                        return _mode;
                    }
                }
                catch { }
				

                bool useDark = Win32Interop.GetSystemTheme(osInfo);
				_mode = useDark ? DarkModeString : LightModeString;
				return _mode;
			}

			if (_mode == LightModeString || _mode == DarkModeString || _mode == HighContrastModeString)
				return _mode;

			_mode = LightModeString; // Default to Mode
			return _mode;
		}

See More Examples