System.Runtime.InteropServices.Marshal.StructureToPtr(T, System.IntPtr, bool)

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

532 Examples 7

19 View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade

public static void CallHooks(Messages Msg, IntPtr wParam, Message lParamMsg, bool global = true, bool window = true, bool allWindows = false) {
            IntPtr lParam = Marshal.AllocHGlobal(MessageSize);
            Marshal.StructureToPtr(lParamMsg, lParam, false);
            CallHooks(Msg, wParam, lParam, lParamMsg: ref lParamMsg, global: global, window: window, allWindows: allWindows);
            Marshal.FreeHGlobal(lParam);
        }

19 View Source File : DMSkinComplexWindow.cs
License : MIT License
Project Creator : 944095635

private void WmNCCalcSize(IntPtr LParam)
        {
            // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/windows/windowreference/windowmessages/wm_nccalcsize.asp
            // http://groups.google.pl/groups?selm=OnRNaGfDEHA.1600%40tk2msftngp13.phx.gbl

            var r = (RECT)Marshal.PtrToStructure(LParam, typeof(RECT));
            //var max = MinMaxState == FormWindowState.Maximized;

            if (WindowState == WindowState.Maximized)
            {
                var x = NativeMethods.GetSystemMetrics(NativeConstants.SM_CXSIZEFRAME);
                var y = NativeMethods.GetSystemMetrics(NativeConstants.SM_CYSIZEFRAME);
                var p = NativeMethods.GetSystemMetrics(NativeConstants.SM_CXPADDEDBORDER);
                var w = x + p;
                var h = y + p;

                r.left += w;
                r.top += h;
                r.right -= w;
                r.bottom -= h;

                var appBarData = new APPBARDATA();
                appBarData.cbSize = Marshal.SizeOf(typeof(APPBARDATA));
                var autohide = (NativeMethods.SHAppBarMessage(NativeConstants.ABM_GETSTATE, ref appBarData) & NativeConstants.ABS_AUTOHIDE) != 0;
                if (autohide) r.bottom -= 1;

                Marshal.StructureToPtr(r, LParam, true);
            }
        }

19 View Source File : DMSkinSimpleWindow.cs
License : MIT License
Project Creator : 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 View Source File : DMSkinComplexWindow.cs
License : MIT License
Project Creator : 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 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : UnmanagedBuffer.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Commit<T>(T data) where T: struct
        {
            try
            {
                if (this.Alloc(Marshal.SizeOf(typeof(T))))
                {
                    Marshal.StructureToPtr(data, this.Pointer, false);
                    return true;
                }
                return false;
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : CreateThread.cs
License : MIT License
Project Creator : Akaion

public void CallFunction(CallDescriptor callDescriptor)
        {
            // Write the shellcode used to perform the function call into a buffer

            var shellcode = replacedembleShellcode(callDescriptor);

            var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);

            _memory.WriteBlock(shellcodeBuffer, shellcode);

            _memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);

            // Create a suspended thread with a spoofed start address

            var ntStatus = Ntdll.NtCreateThreadEx(out var threadHandle, AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, IntPtr.Zero, _process.SafeHandle, _process.MainModule.BaseAddress, IntPtr.Zero, ThreadCreationFlags.CreateSuspended | ThreadCreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);

            if (ntStatus != NtStatus.Success)
            {
                throw new Win32Exception($"Failed to call NtCreateThreadEx with error code {ntStatus}");
            }

            if (callDescriptor.IsWow64Call)
            {
                // Get the context of the thread

                var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Integer};

                if (!Kernel32.Wow64GetThreadContext(threadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                // Change the spoofed start address to the address of the shellcode

                threadContext.Eax = (int) shellcodeBuffer;

                // Update the context of the thread

                if (!Kernel32.Wow64SetThreadContext(threadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }
            }

            else
            {
                // Get the context of the thread

                var threadContext = new Context {ContextFlags = ContextFlags.Integer};

                var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                if (!Kernel32.GetThreadContext(threadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);

                // Change the spoofed start address to the address of the shellcode

                threadContext.Rcx = (long) shellcodeBuffer;

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                // Update the context of the thread

                if (!Kernel32.SetThreadContext(threadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                Marshal.FreeHGlobal(threadContextBuffer);
            }

            // Resume the thread

            if (Kernel32.ResumeThread(threadHandle) == -1)
            {
                throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
            }

            if (Kernel32.WaitForSingleObject(threadHandle, int.MaxValue) == -1)
            {
                throw new Win32Exception($"Failed to call WaitForSingleObject with error code {Marshal.GetLastWin32Error()}");
            }

            threadHandle.Dispose();

            _memory.FreeBlock(shellcodeBuffer);
        }

19 View Source File : HijackThread.cs
License : MIT License
Project Creator : Akaion

public void CallFunction(CallDescriptor callDescriptor)
        {
            var completionFlagBuffer = _memory.AllocateBlock(IntPtr.Zero, sizeof(bool), ProtectionType.ReadWrite);

            // Write the shellcode used to perform the function call into a buffer

            var shellcode = replacedembleShellcode(callDescriptor, completionFlagBuffer);

            var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);

            _memory.WriteBlock(shellcodeBuffer, shellcode);

            _memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);

            // Open a handle to the first thread

            var firstThreadHandle = Kernel32.OpenThread(AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, false, _process.Threads[0].Id);

            if (firstThreadHandle.IsInvalid)
            {
                throw new Win32Exception($"Failed to call OpenThread with error code {Marshal.GetLastWin32Error()}");
            }

            if (callDescriptor.IsWow64Call)
            {
                // Suspend the thread

                if (Kernel32.Wow64SuspendThread(firstThreadHandle) == -1)
                {
                    throw new Win32Exception($"Failed to call Wow64SuspendThread with error code {Marshal.GetLastWin32Error()}");
                }

                // Get the context of the thread

                var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Control};

                if (!Kernel32.Wow64GetThreadContext(firstThreadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                // Write the original instruction pointer of the thread into the top of its stack

                threadContext.Esp -= sizeof(int);

                _memory.Write((IntPtr) threadContext.Esp, threadContext.Eip);

                // Overwrite the instruction pointer of the thread with the address of the shellcode

                threadContext.Eip = (int) shellcodeBuffer;

                // Update the context of the thread

                if (!Kernel32.Wow64SetThreadContext(firstThreadHandle, ref threadContext))
                {
                    throw new Win32Exception($"Failed to call Wow64SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }
            }

            else
            {
                // Suspend the thread

                if (Kernel32.SuspendThread(firstThreadHandle) == -1)
                {
                    throw new Win32Exception($"Failed to call SuspendThread with error code {Marshal.GetLastWin32Error()}");
                }

                // Get the context of the thread

                var threadContext = new Context {ContextFlags = ContextFlags.Control};

                var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                if (!Kernel32.GetThreadContext(firstThreadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);

                // Write the original instruction pointer of the thread into the top of its stack

                threadContext.Rsp -= sizeof(long);

                _memory.Write((IntPtr) threadContext.Rsp, threadContext.Rip);

                // Overwrite the instruction pointer of the thread with the address of the shellcode

                threadContext.Rip = (long) shellcodeBuffer;

                Marshal.StructureToPtr(threadContext, threadContextBuffer, false);

                // Update the context of the thread

                if (!Kernel32.SetThreadContext(firstThreadHandle, threadContextBuffer))
                {
                    throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
                }

                Marshal.FreeHGlobal(threadContextBuffer);
            }

            // Send a message to the thread to ensure it executes the shellcode

            if (!User32.PostThreadMessage(_process.Threads[0].Id, MessageType.Null, IntPtr.Zero, IntPtr.Zero))
            {
                throw new Win32Exception($"Failed to call PostThreadMessage with error code {Marshal.GetLastWin32Error()}");
            }

            // Resume the thread

            if (Kernel32.ResumeThread(firstThreadHandle) == -1)
            {
                throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
            }

            while (!_memory.Read<bool>(completionFlagBuffer))
            {
                Thread.Sleep(1);
            }

            firstThreadHandle.Dispose();

            _memory.FreeBlock(shellcodeBuffer);

            _memory.FreeBlock(completionFlagBuffer);
        }

19 View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho

public static byte[] StructToBytes<T>(T structObj) where T : struct
        {
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(structObj);
            //创建byte数组
            var bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

19 View Source File : Window.cs
License : MIT License
Project Creator : 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 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static byte[] ToByteArray<T>(T obj)
                where T : struct
            {
                IntPtr ptr = IntPtr.Zero;
                try
                {
                    int size = Marshal.SizeOf(typeof(T));
                    ptr = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(obj, ptr, true);
                    byte[] bytes = new byte[size];
                    Marshal.Copy(ptr, bytes, 0, size);
                    return bytes;
                }
                finally
                {
                    if (ptr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }
                }
            }

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : 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 View Source File : Includer.cs
License : MIT License
Project Creator : 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 View Source File : IDWriteGdiInterop1.cs
License : MIT License
Project Creator : 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 View Source File : IDWriteGdiInterop.cs
License : MIT License
Project Creator : 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 View Source File : IDWriteGdiInterop1.cs
License : MIT License
Project Creator : 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 View Source File : CoreWindow.cs
License : MIT License
Project Creator : amwx

protected override IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
		{
			switch ((WM)msg)
			{
				case WM.NCCALCSIZE:
					// Follows logic from how to extend window frame + WindowsTerminal + Firefox
					// Windows Terminal only handles WPARAM = TRUE & only adjusts the top of the
					// rgrc[0] RECT & gets the correct result
					// Firefox, on the other hand, handles BOTH times WM_NCCALCSIZE is called,
					// and modifies the RECT.
					// This particularly differs from the "built-in" method in Avalonia in that
					// I retain the SystemBorder & ability resize the window in the transparent
					// area over the drop shadows, meaning resize handles don't overlap the window

					if (wParam != IntPtr.Zero)
					{
						var ncParams = Marshal.PtrToStructure<NCCALCSIZE_PARAMS>(lParam);

						var originalTop = ncParams.rgrc[0].top;

						var ret = Win32Interop.DefWindowProc(hWnd, (uint)WM.NCCALCSIZE, wParam, lParam);
						if (ret != IntPtr.Zero)
							return ret;

						var newSize = ncParams.rgrc[0];
						newSize.top = originalTop;

						if (WindowState == WindowState.Maximized)
						{
							newSize.top += GetResizeHandleHeight();
						}

						newSize.left += 8;
						newSize.right -= 8;
						newSize.bottom -= 8;

						ncParams.rgrc[0] = newSize;

						Marshal.StructureToPtr(ncParams, lParam, true);

						return IntPtr.Zero;
					}

					return IntPtr.Zero;

				case WM.NCHITTEST:
					return HandleNCHitTest(lParam);

				case WM.SIZE:
					EnsureExtended();
					break;

				case WM.NCMOUSEMOVE:
					if (_fakingMaximizeButton)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizeHover(_owner.HitTestMaximizeButton(point));
						return IntPtr.Zero;
					}
					break;

				case WM.NCLBUTTONDOWN:
					if (_fakingMaximizeButton)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizePressed(_owner.HitTestMaximizeButton(point));
						_wasFakeMaximizeDown = true;

						// This is important. If we don't tell the System we've handled this, we'll get that
						// clreplacedic Win32 button showing when we mouse press, and that's not good
						return IntPtr.Zero;
					}
					break;

				case WM.NCLBUTTONUP:
					if (_fakingMaximizeButton && _wasFakeMaximizeDown)
					{
						var point = PointToClient(PointFromLParam(lParam));
						_owner.FakeMaximizePressed(false);
						_wasFakeMaximizeDown = false;
						_owner.FakeMaximizeClick();
						return IntPtr.Zero;
					}
					break;
			}

			return base.WndProc(hWnd, msg, wParam, lParam);
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : Analogy-LogViewer

private static IntPtr IntPtrAlloc<T>(T param)
        {
            IntPtr retval = Marshal.AllocHGlobal(Marshal.SizeOf(param));
            Marshal.StructureToPtr(param, retval, false);
            return retval;
        }

19 View Source File : TestUtils.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

public static unsafe void AddStruct(long fileId, ContainerType container)
        {
            long res;

            var dims = new ulong[] { 2, 2, 3 }; /* "extendible contiguous non-external dataset not allowed" */

            // non-nullable struct
            var typeId = TestUtils.GetHdfTypeIdFromType(typeof(TestStructL1));
            TestUtils.Add(container, fileId, "struct", "nonnullable", typeId, TestData.NonNullableStructData.replacedpan(), dims);
            res = H5T.close(typeId);

            // nullable struct
            var typeIdNullable = TestUtils.GetHdfTypeIdFromType(typeof(TestStructString));
            var dataNullable = TestData.StringStructData;

            // There is also Unsafe.SizeOf<T>() to calculate managed size instead of native size.
            // Is only relevant when Marshal.XX methods are replaced by other code.
            var elementSize = Marshal.SizeOf<TestStructString>();
            var totalByteLength = elementSize * dataNullable.Length;
            var dataNullablePtr = Marshal.AllocHGlobal(totalByteLength);
            var counter = 0;

            dataNullable.Cast<ValueType>().ToList().ForEach(x =>
            {
                var sourcePtr = Marshal.AllocHGlobal(elementSize);
                Marshal.StructureToPtr(x, sourcePtr, false);

                var source = new Span<byte>(sourcePtr.ToPointer(), elementSize);
                var target = new Span<byte>(IntPtr.Add(dataNullablePtr, elementSize * counter).ToPointer(), elementSize);

                source.CopyTo(target);
                counter++;
                Marshal.FreeHGlobal(sourcePtr);
            });

            TestUtils.Add(container, fileId, "struct", "nullable", typeIdNullable, dataNullablePtr.ToPointer(), dims);

            Marshal.FreeHGlobal(dataNullablePtr);
            res = H5T.close(typeIdNullable);
        }

19 View Source File : GetInjectedThreads.cs
License : MIT License
Project Creator : Apr4h

static void GetLogonSessionData(IntPtr hToken, InjectedThread injectedThread)
        {
            int tokenInformationLength = 0;
            bool result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLreplaced.TokenOrigin, IntPtr.Zero, tokenInformationLength, out tokenInformationLength);
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInformationLength);

            result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLreplaced.TokenOrigin, tokenInformation, tokenInformationLength, out tokenInformationLength);

            if(result)
            {
                // GetTokenInformation to retreive LUID struct
                TOKEN_ORIGIN tokenOrigin = (TOKEN_ORIGIN)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_ORIGIN));
                IntPtr pLUID = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID)));  
                
                // Get pointer to LUID struct for LsaGetLogonSessionData
                Marshal.StructureToPtr(tokenOrigin.OriginatingLogonSession, pLUID, false);

                IntPtr pLogonSessionData = IntPtr.Zero;
                LsaGetLogonSessionData(pLUID, out pLogonSessionData);

                SECURITY_LOGON_SESSION_DATA logonSessionData = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(pLogonSessionData, typeof(SECURITY_LOGON_SESSION_DATA));

                // Check for a valid logon 
                if(logonSessionData.PSiD != IntPtr.Zero)
                {
                    if(injectedThread.Username.Equals("NO OWNER"))
                    {
                        string domain = Marshal.PtrToStringUni(logonSessionData.LoginDomain.buffer).Trim();
                        string username = Marshal.PtrToStringUni(logonSessionData.Username.buffer).Trim();
                        injectedThread.Username = $"{domain}\\{username}";
                    }

                    // Add logon session information to InjectedThread object
                    injectedThread.LogonSessionStartTime = DateTime.FromFileTime(logonSessionData.LoginTime);
                    injectedThread.LogonType = Enum.GetName(typeof(SECURITY_LOGON_TYPES), logonSessionData.LogonType);  
                    injectedThread.AuthenticationPackage = Marshal.PtrToStringAuto(logonSessionData.AuthenticationPackage.buffer);
                }

                LsaFreeReturnBuffer(pLogonSessionData);
            }
        }

19 View Source File : Gw2ChatLink.cs
License : MIT License
Project Creator : Archomeda

protected static unsafe byte[] ToArray<T>(T chatLinkStruct, ChatLinkType? chatLinkType) where T : struct
        {
            int startPos = chatLinkType.HasValue ? 1 : 0;
            int structSize = Marshal.SizeOf(typeof(T));
            byte[] bytes = new byte[structSize + startPos];

            if (chatLinkType.HasValue)
                bytes[0] = (byte)chatLinkType;
            fixed (byte* ptr = &bytes[startPos])
            {
                var intPtr = new IntPtr(ptr);
                Marshal.StructureToPtr(chatLinkStruct, intPtr, true);
            }

            return bytes;
        }

19 View Source File : AlignedArray.cs
License : GNU General Public License v2.0
Project Creator : ArgusMagnus

protected virtual void SetCore(T value, IntPtr ptr) => Marshal.StructureToPtr<T>(value, ptr, false);

19 View Source File : Functions.cs
License : MIT License
Project Creator : arsium

internal static int SetAero10(IntPtr hwnd)
		{
			NativeAPI.Miscellaneous.AccentPolicy accentPolicy = new NativeAPI.Miscellaneous.AccentPolicy
			{
				AccentState = NativeAPI.Miscellaneous.AccentState.ACCENT_ENABLE_BLURBEHIND,
				AccentFlags = 0,
				GradientColor = 0,
				AnimationId = 0
			};
			NativeAPI.Miscellaneous.WindowCompositionAttributeData data = new NativeAPI.Miscellaneous.WindowCompositionAttributeData { Attribute = NativeAPI.Miscellaneous.WindowCompositionAttribute.WCA_ACCENT_POLICY };
			int accentSize = Marshal.SizeOf(accentPolicy);
			IntPtr accentPtr = Marshal.AllocHGlobal(accentSize);
			Marshal.StructureToPtr(accentPolicy, accentPtr, false);
			data.Data = accentPtr;
			data.SizeOfData = accentSize;
			int result = NativeAPI.Miscellaneous.SetWindowCompositionAttribute(hwnd, ref data);
			Marshal.FreeHGlobal(accentPtr);
			return result;
		}

19 View Source File : DLLFromMemory.cs
License : MIT License
Project Creator : arsium

static void PtrWrite<T>(IntPtr ptr, T val) { Marshal.StructureToPtr(val, ptr, false); }

19 View Source File : BitConverterEx.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

public static byte[] GetBytes<T>(T value)
        {
            int size;
            byte[] buffer;
            BufferBase dst;
            if (!typeof(T).IsArray)
            {
                size = Memory.SizeOf(typeof(T));
                buffer = new byte[size];
                using (dst = BufferBase.Wrap(buffer))
                {
                    Marshal.StructureToPtr(value, dst.Pin(), true);
                    dst.UnPin();
                }
            }
            else
            {
                size = Memory.SizeOf(typeof(T).GetElementType()) *
                       (int)typeof(T).GetProperty("Length").GetValue(value, null);
                buffer = new byte[size];
                using (dst = BufferBase.Wrap(buffer))
                {
                    using (var src = BufferBase.Wrap(value as Array, size))
                        Memory.Copy(src, dst, size);
                }
            }

            return buffer;
        }

19 View Source File : AyMessageBox.xaml.cs
License : MIT License
Project Creator : ay2015

private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
    {

        MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

        // Adjust the maximized size and position to fit the work area of the correct monitor
        int MONITOR_DEFAULTTONEAREST = 0x00000002;
        System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

        if (monitor != System.IntPtr.Zero)
        {

            MONITORINFO monitorInfo = new MONITORINFO();
            GetMonitorInfo(monitor, monitorInfo);
            RECT rcWorkArea = monitorInfo.rcWork;
            RECT rcMonitorArea = monitorInfo.rcMonitor;
            mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
            mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
            mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
            mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
        }

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

19 View Source File : Generator.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public unsafe static int CreateInstance(ref DSConfig config)
        {
            byte[] bytes;
            UInt32 inst_len = Convert.ToUInt32(Marshal.SizeOf(typeof(DSInstance)));

            D.Print("Entering CreateInstance()");

            // Initialize Instance struct
            DSInstance inst = new Helper().InitStruct("DSInstance");

            // Add module size to instance len
            if (config.inst_type == Constants.DONUT_INSTANCE_PIC)
            {
                D.Print($"Adding module size {config.mod_len} to instance size");
                inst_len += Convert.ToUInt32(Marshal.SizeOf(typeof(DSModule)) + 32) + Convert.ToUInt32(config.mod_len);
            }

            // Generate instance key and counter
            bytes = Helper.RandomBytes(32);
            for (var i = 0; i < bytes.Length; i++)
            {
                if (i < 16)
                {
                    inst.key.ctr[i] = bytes[i];
                }
                else
                {
                    inst.key.mk[i - 16] = bytes[i];
                }
            }
            D.Print($"Instance CTR:\t{BitConverter.ToString(inst.key.ctr).Replace("-", "")}");
            D.Print($"Instance MK :\t{BitConverter.ToString(inst.key.mk).Replace("-", "")}");

            // Generate module key and counter
            bytes = Helper.RandomBytes(32);
            for (var i = 0; i < bytes.Length; i++)
            {
                if (i < 16)
                {
                    inst.mod_key.ctr[i] = bytes[i];
                }
                else
                {
                    inst.mod_key.mk[i - 16] = bytes[i];
                }
            }
            D.Print($"Module CTR:\t{BitConverter.ToString(inst.mod_key.ctr).Replace("-", "")}");
            D.Print($"Module MK :\t{BitConverter.ToString(inst.mod_key.mk).Replace("-", "")}");

            // Create Verifier string
            Helper.Copy(inst.sig, Helper.RandomString(8));
            D.Print($"Decryption Verfier String: {Helper.String(inst.sig)}");

            // Create IV
            inst.iv = BitConverter.ToUInt64(Helper.RandomBytes(8), 0);
            D.Print($"IV for Maru Hash:\t{BitConverter.ToString(bytes).Replace("-", "")}");

            // Generate DLL and API hashes
            Helper.APIImports(ref inst);

            // replacedign GUIDs and other vals
            if (config.mod_type == Constants.DONUT_MODULE_NET_DLL || config.mod_type == Constants.DONUT_MODULE_NET_EXE)
            {
                inst.xIID_AppDomain = Constants.xIID_AppDomain;
                inst.xIID_ICLRMetaHost = Constants.xIID_ICLRMetaHost;
                inst.xCLSID_CLRMetaHost = Constants.xCLSID_CLRMetaHost;
                inst.xIID_ICLRRuntimeInfo = Constants.xIID_ICLRRuntimeInfo;
                inst.xIID_ICorRuntimeHost = Constants.xIID_ICorRuntimeHost;
                inst.xCLSID_CorRuntimeHost = Constants.xCLSID_CorRuntimeHost;
            }
            else if (config.mod_type == Constants.DONUT_MODULE_VBS || config.mod_type == Constants.DONUT_MODULE_JS)
            {
                inst.xIID_IUnknown = Constants.xIID_IUnknown;
                inst.xIID_IDispatch = Constants.xIID_IDispatch;
                inst.xIID_IHost = Constants.xIID_IHost;
                inst.xIID_IActiveScript = Constants.xIID_IActiveScript;
                inst.xIID_IActiveScriptSite = Constants.xIID_IActiveScriptSite;
                inst.xIID_IActiveScriptSiteWindow = Constants.xIID_IActiveScriptSiteWindow;
                inst.xIID_IActiveScriptParse32 = Constants.xIID_IActiveScriptParse32;
                inst.xIID_IActiveScriptParse64 = Constants.xIID_IActiveScriptParse64;

                Helper.Copy(inst.wscript, "WScript");
                Helper.Copy(inst.wscript_exe, "wscript.exe");

                if (config.mod_type == Constants.DONUT_MODULE_VBS)
                {
                    inst.xCLSID_ScriptLanguage = Constants.xCLSID_VBScript;
                }
                else
                {
                    inst.xCLSID_ScriptLanguage = Constants.xCLSID_JScript;
                }
            }
            else if (config.mod_type == Constants.DONUT_MODULE_XSL)
            {
                inst.xCLSID_DOMDoreplacedent30 = Constants.xCLSID_DOMDoreplacedent30;
                inst.xIID_IXMLDOMDoreplacedent = Constants.xIID_IXMLDOMDoreplacedent;
                inst.xIID_IXMLDOMNode = Constants.xIID_IXMLDOMNode;
            }

            Helper.Copy(inst.amsi.s, "AMSI");
            Helper.Copy(inst.amsiInit, "AmsiInitialize");
            Helper.Copy(inst.amsiScanBuf, "AmsiScanBuffer");
            Helper.Copy(inst.amsiScanStr, "AmsiScanString");
            Helper.Copy(inst.clr, "CLR");
            Helper.Copy(inst.wldp, "WLDP");
            Helper.Copy(inst.wldpQuery, "WldpQueryDynamicCodeTrust");
            Helper.Copy(inst.wldpIsApproved, "WldpIsClreplacedInApprovedList");

            // replacedign inst type
            inst.type = config.inst_type;

            // If URL type, replacedign URL
            if (inst.type == Constants.DONUT_INSTANCE_URL)
            {
                inst.http.url = new char[Constants.DONUT_MAX_URL];
                inst.http.req = new char[8];
                config.modname = Helper.RandomString(Constants.DONUT_MAX_MODNAME).ToCharArray();
                Helper.Copy(inst.http.url, Helper.String(config.url) + Helper.String(config.modname));
                Helper.Copy(inst.http.req, "GET");

                D.Print($"Payload will be downloaded from {Helper.String(inst.http.url)}");
            }

            // Update struct lengths
            inst.mod_len = config.mod_len;
            inst.len = inst_len;
            config.inst = inst;
            config.inst_len = inst_len;

            // Generate MAC
            inst.mac = Helper.Maru(Helper.String(inst.sig), ref inst);

            // Copy Instance to memory
            var instptr = Marshal.AllocHGlobal(Convert.ToInt32(config.inst_len));
            Marshal.StructureToPtr(inst, instptr, false);

            // Copy Module to memory
            var modptr = Marshal.AllocHGlobal(Convert.ToInt32(config.mod_len));
            Marshal.StructureToPtr(config.mod, modptr, false);

            // Calculate offsets
            var encoffset = Marshal.OffsetOf(typeof(DSInstance), "api_cnt").ToInt32();
            var encptr = IntPtr.Add(instptr, encoffset);
            var modoffset = Marshal.OffsetOf(typeof(DSInstance), "module").ToInt32();
            var moddata = IntPtr.Add(instptr, modoffset);
            var fileoffset = Marshal.OffsetOf(typeof(DSModule), "data").ToInt32();

            // Copy Module to Instance
            Buffer.MemoryCopy(modptr.ToPointer(), moddata.ToPointer(), Marshal.SizeOf(typeof(DSModule)), Marshal.SizeOf(typeof(DSModule)));

            // if URL, copy stuff
            if (inst.type == Constants.DONUT_INSTANCE_URL)
            {
                D.Print($"Copying URL module data to instance");
                //inst.module.p = config.mod;
            }

            // if PIC, copy payload to instance
            if (inst.type == Constants.DONUT_INSTANCE_PIC)
            {
                D.Print($"Copying PIC module data to instance");
                // Copy payload file to end of module
                var mmfile = MemoryMappedFile.CreateFromFile(Helper.String(config.file), FileMode.Open);
                var view = mmfile.CreateViewAccessor();
                byte* fileptr = (byte*)0;
                view.SafeMemoryMappedViewHandle.AcquirePointer(ref fileptr);
                Buffer.MemoryCopy(fileptr, IntPtr.Add(moddata, fileoffset).ToPointer(), config.mod.len, config.mod.len);
                mmfile.Dispose();
            }

            // Release module
            Marshal.FreeHGlobal(modptr);

            // Encrypt instance
            D.Print("Encrypting Instance");
            Helper.Encrypt(inst.key.mk, inst.key.ctr, encptr, Convert.ToUInt32(inst.len - encoffset));

            // Writes raw instance if DEBUG
            D.WriteInst(config, instptr);

            // Generate final shellcode
            int ret = Shellcode(ref config, instptr);
            if (ret != Constants.DONUT_ERROR_SUCCESS)
            {
                Console.WriteLine("[x] Error " + Helper.GetError(ret));
                return ret;
            }
            return Constants.DONUT_ERROR_SUCCESS;
        }

19 View Source File : Spawner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public static bool CreateProcess(string processname, int ppid, Natives.CreationFlags cf, ref Natives.PROCESS_INFORMATION procInfo)
        {
            Natives.STARTUPINFOEX sInfoEx = new Natives.STARTUPINFOEX();

            sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx);
            IntPtr lpValue = IntPtr.Zero;

            Natives.SECURITY_ATTRIBUTES pSec = new Natives.SECURITY_ATTRIBUTES();
            Natives.SECURITY_ATTRIBUTES tSec = new Natives.SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            tSec.nLength = Marshal.SizeOf(tSec);

            IntPtr pntpSec = Marshal.AllocHGlobal(Marshal.SizeOf(pSec));
            Marshal.StructureToPtr(pSec, pntpSec, false);
            IntPtr pnttSec = Marshal.AllocHGlobal(Marshal.SizeOf(tSec));
            Marshal.StructureToPtr(tSec, pnttSec, false);

            IntPtr lpSize = IntPtr.Zero;

            Natives.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
            sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
            Natives.InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize);

            IntPtr parentHandle = Process.GetProcessById(ppid).Handle;
            lpValue = Marshal.AllocHGlobal(IntPtr.Size);
            Marshal.WriteIntPtr(lpValue, parentHandle);

            Natives.UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)Natives.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero);

            if (!Natives.CreateProcess(IntPtr.Zero, processname, pntpSec, pnttSec, false, (uint)cf, IntPtr.Zero, IntPtr.Zero, ref sInfoEx, out procInfo))
            {
                return false;
            }

            return true;
        }

19 View Source File : Spawner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public static bool CreateProcessPCMPBNMBSAO(IntPtr hReadPipe, IntPtr hWritePipe, string processname, bool inheritHandler, ref Natives.PROCESS_INFORMATION procInfo)
        {
            Natives.SetHandleInformation(hReadPipe, Natives.HANDLE_FLAGS.INHERIT, 0);

            Natives.STARTUPINFOEX sInfoEx = new Natives.STARTUPINFOEX();

            sInfoEx.StartupInfo.hStdOutput = hWritePipe;
            sInfoEx.StartupInfo.hStdErr = hWritePipe;
            sInfoEx.StartupInfo.dwFlags = Natives.STARTF_USESTDHANDLES;

            IntPtr lpValue = IntPtr.Zero;

            Natives.SECURITY_ATTRIBUTES pSec = new Natives.SECURITY_ATTRIBUTES();
            Natives.SECURITY_ATTRIBUTES tSec = new Natives.SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            tSec.nLength = Marshal.SizeOf(tSec);

            IntPtr pntpSec = Marshal.AllocHGlobal(Marshal.SizeOf(pSec));
            Marshal.StructureToPtr(pSec, pntpSec, false);
            IntPtr pnttSec = Marshal.AllocHGlobal(Marshal.SizeOf(tSec));
            Marshal.StructureToPtr(tSec, pnttSec, false);

            IntPtr lpSize = IntPtr.Zero;

            Natives.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
            sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
            Natives.InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize);

            Natives.DWORD64 policy = new Natives.DWORD64();
            policy.dwPart1 = 0;
            policy.dwPart2 = 0x1000;

            lpValue = Marshal.AllocHGlobal(Marshal.SizeOf(policy));
            Marshal.StructureToPtr(policy, lpValue, false);

            Natives.UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)Natives.PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, lpValue, (IntPtr)Marshal.SizeOf(policy), IntPtr.Zero, IntPtr.Zero);

            sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx);

            if (!Natives.CreateProcess(IntPtr.Zero, processname, IntPtr.Zero, IntPtr.Zero, inheritHandler, Natives.CreateSuspended | (uint)Natives.CreationFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, IntPtr.Zero, ref sInfoEx, out procInfo))
            {
                return false;
            }
            return true;
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

public static void Execute(string[] args)
        {
            if (IntPtr.Size != 8)
            {
                return;
            }

            if (!IsElevated())
            {
                Console.WriteLine("Run in High integrity context");
                return;
            }

            SetDebugPrivilege();

            Natives.WIN_VER_INFO pWinVerInfo = new Natives.WIN_VER_INFO();

            Natives.OSVERSIONINFOEXW osInfo = new Natives.OSVERSIONINFOEXW();
            osInfo.dwOSVersionInfoSize = Marshal.SizeOf(osInfo);

            Natives.RtlGetVersion(ref osInfo);

            pWinVerInfo.chOSMajorMinor = osInfo.dwMajorVersion + "." + osInfo.dwMinorVersion;

            Console.WriteLine("[*] OS MajorMinor version : " + pWinVerInfo.chOSMajorMinor);
            if(!pWinVerInfo.chOSMajorMinor.Equals("10.0"))
            {
                Console.WriteLine("[x] Windows 10 - Windows Server 2016 only");
                return;
            }

            pWinVerInfo.SystemCall = 0x3F;

            Natives.RtlInitUnicodeString(ref pWinVerInfo.ProcName, @"lsreplaced.exe");
            pWinVerInfo.hTargetPID = (IntPtr)Process.GetProcessesByName("lsreplaced")[0].Id;

            pWinVerInfo.lpApiCall = "NtReadVirtualMemory";

            if (!UnHookNativeApi(pWinVerInfo))
            {
                Console.WriteLine("[x] error unhooking {0}", pWinVerInfo.lpApiCall);
                return;
            }

            Natives.CLIENT_ID clientid = new Natives.CLIENT_ID();
            clientid.UniqueProcess = pWinVerInfo.hTargetPID;
            clientid.UniqueThread = IntPtr.Zero;

            IntPtr hProcess = IntPtr.Zero;

            Natives.OBJECT_ATTRIBUTES objAttribute = new Natives.OBJECT_ATTRIBUTES();


            var status = NativeSysCall.ZwOpenProcess10(ref hProcess, Natives.ProcessAccessFlags.All, objAttribute, ref clientid);

            if (hProcess == IntPtr.Zero)
            {
                Console.WriteLine("[x] Error ZwOpenProcess10  " + status);
                return;
            }

            Console.WriteLine("[*] ZwOpenProcess10  " + status);

            Natives.PSS_CAPTURE_FLAGS flags = Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_VA_CLONE
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLES
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_NAME_INFORMATION
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_BASIC_INFORMATION
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_TRACE
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREADS
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREAD_CONTEXT
        | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREAD_CONTEXT_EXTENDED
        | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_BREAKAWAY
        | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_BREAKAWAY_OPTIONAL
        | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_USE_VM_ALLOCATIONS
        | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_RELEASE_SECTION;

            IntPtr SnapshotHandle = IntPtr.Zero;
            int pss = Natives.PssCaptureSnapshot(hProcess,flags, 1048607,ref SnapshotHandle);
            Console.WriteLine("[*] PssCaptureSnapshot " + pss);
            if (SnapshotHandle == IntPtr.Zero)
            {
                Console.WriteLine("[x] Error PssCaptureSnapshot  ");
                return;
            }

            Natives.UNICODE_STRING uFileName = new Natives.UNICODE_STRING();
            Natives.RtlInitUnicodeString(ref uFileName, @"\??\C:\Windows\Temp\dumpert.dmp");

            Microsoft.Win32.SafeHandles.SafeFileHandle hDmpFile;
            IntPtr hElm = IntPtr.Zero;
            Natives.IO_STATUS_BLOCK IoStatusBlock = new Natives.IO_STATUS_BLOCK();

            IntPtr objectName = Marshal.AllocHGlobal(Marshal.SizeOf(uFileName));
            Marshal.StructureToPtr(uFileName, objectName, true);

            Natives.OBJECT_ATTRIBUTES FileObjectAttributes = new Natives.OBJECT_ATTRIBUTES
            {
                ObjectName = objectName,
                Attributes = 0x00000040,
                Length = (ulong)Marshal.SizeOf(typeof(Natives.OBJECT_ATTRIBUTES)),
                RootDirectory = IntPtr.Zero,
                SecurityDescriptor = IntPtr.Zero,
                SecurityQualityOfService = IntPtr.Zero
            };

            Natives.LARGE_INTEGER lint = new Natives.LARGE_INTEGER();
            lint.HighPart = 0;
            lint.LowPart = 0;

            long allocationsize = 0;

            status = NativeSysCall.NtCreateFile10(
                out hDmpFile,
                (int)Natives.FILE_GENERIC_WRITE,
                ref FileObjectAttributes,
                out IoStatusBlock,
                ref allocationsize,
                Natives.FILE_ATTRIBUTE_NORMAL,
                System.IO.FileShare.Write,
                Natives.FILE_OVERWRITE_IF,
                Natives.FILE_SYNCHRONOUS_IO_NONALERT,
                hElm, 0);

            if (hDmpFile.IsInvalid)
            {
                Console.WriteLine("[x] Error NtCreateFile10  " + status + " " + IoStatusBlock.status);
                NativeSysCall.ZwClose10(hProcess);
                return;
            }

            
            Natives.MINIDUMP_CALLBACK_INFORMATION CallbackInfo = new Natives.MINIDUMP_CALLBACK_INFORMATION();
            CallbackInfo.CallbackRoutine = Program.MyMiniDumpWriteDumpCallback;
            CallbackInfo.CallbackParam = IntPtr.Zero;

            IntPtr pCallbackInfo = Marshal.AllocHGlobal(Marshal.SizeOf(CallbackInfo));
            Marshal.StructureToPtr(CallbackInfo, pCallbackInfo, false);

            IntPtr ExceptionParam = IntPtr.Zero;
            IntPtr UserStreamParam = IntPtr.Zero;
            IntPtr CallbackParam = IntPtr.Zero;

            Console.WriteLine("[*] Target PID " + pWinVerInfo.hTargetPID);
            Console.WriteLine("[*] Generating minidump.... " + pWinVerInfo.hTargetPID);
            
            if (!Natives.MiniDumpWriteDump(SnapshotHandle, (uint)pWinVerInfo.hTargetPID, hDmpFile, 2, ExceptionParam, UserStreamParam, pCallbackInfo))
            {
                Console.WriteLine("[x] Error MiniDumpWriteDump  ");
                NativeSysCall.ZwClose10(hProcess);
                return;
            }

            hDmpFile.Dispose();
            NativeSysCall.ZwClose10(hProcess);

            Console.WriteLine("[*] End ");
            Console.WriteLine("[*] Minidump generated in  " + Marshal.PtrToStringUni(uFileName.Buffer).Substring(4));
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik

private static bool TokenIsElevated(IntPtr hToken)
        {
            Natives.TOKEN_ELEVATION tk = new Natives.TOKEN_ELEVATION();
            tk.TokenIsElevated = 0;
            
            IntPtr lpValue = Marshal.AllocHGlobal(Marshal.SizeOf(tk));
            Marshal.StructureToPtr(tk, lpValue, false);

            UInt32 tokenInformationLength = (UInt32)Marshal.SizeOf(typeof(Natives.TOKEN_ELEVATION));
            UInt32 returnLength;

            Boolean result = Natives.GetTokenInformation(
                hToken,
                Natives.TOKEN_INFORMATION_CLreplaced.TokenElevation,
                lpValue,
                tokenInformationLength,
                out returnLength
            );

            Natives.TOKEN_ELEVATION elv = (Natives.TOKEN_ELEVATION)Marshal.PtrToStructure(lpValue, typeof(Natives.TOKEN_ELEVATION));
            
            if (elv.TokenIsElevated == 1)
            {             
                return true;
            }
            else
            {

                return false;
            }
        }

19 View Source File : WindowChromeBehavior.cs
License : Apache License 2.0
Project Creator : beckzhu

private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            var returnval = IntPtr.Zero;

            switch (msg)
            {
                case (int)WM.NCPAINT:
                    handled = this.GlreplacedFrameThickness == default(Thickness) && this.GlowBrush == null;
                    break;

                case (int)WM.WINDOWPOSCHANGING:
                {
                    var pos = (WINDOWPOS)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
                    if ((pos.flags & SWP.NOMOVE) != 0)
                    {
                        return IntPtr.Zero;
                    }

                    var wnd = this.replacedociatedObject;
                    if (wnd == null || this.hwndSource?.CompositionTarget == null)
                    {
                        return IntPtr.Zero;
                    }

                    var changedPos = false;

                    // Convert the original to original size based on DPI setting. Need for x% screen DPI.
                    var matrix = this.hwndSource.CompositionTarget.TransformToDevice;

                    var minWidth = wnd.MinWidth * matrix.M11;
                    var minHeight = wnd.MinHeight * matrix.M22;
                    if (pos.cx < minWidth) { pos.cx = (int)minWidth; changedPos = true; }
                    if (pos.cy < minHeight) { pos.cy = (int)minHeight; changedPos = true; }

                    var maxWidth = wnd.MaxWidth * matrix.M11;
                    var maxHeight = wnd.MaxHeight * matrix.M22;
                    if (pos.cx > maxWidth && maxWidth > 0) { pos.cx = (int)Math.Round(maxWidth); changedPos = true; }
                    if (pos.cy > maxHeight && maxHeight > 0) { pos.cy = (int)Math.Round(maxHeight); changedPos = true; }

                    if (!changedPos)
                    {
                        return IntPtr.Zero;
                    }

                    System.Runtime.InteropServices.Marshal.StructureToPtr(pos, lParam, true);
                    handled = true;
                }
                    break;
            }

            return returnval;
        }

19 View Source File : SystemParameters2.cs
License : Apache License 2.0
Project Creator : beckzhu

[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        private void _InitializeCaptionButtonLocation()
        {
            // There is a completely different way to do this on XP.
            if (!Utility.IsOSVistaOrNewer || !NativeMethods.IsThemeActive())
            {
                _LegacyInitializeCaptionButtonLocation();
                return;
            }

            var tbix = new replacedLEBARINFOEX { cbSize = Marshal.SizeOf(typeof(replacedLEBARINFOEX)) };
            IntPtr lParam = Marshal.AllocHGlobal(tbix.cbSize);
            try
            {
                Marshal.StructureToPtr(tbix, lParam, false);
                // This might flash a window in the taskbar while being calculated.
                // WM_GETreplacedLEBARINFOEX doesn't work correctly unless the window is visible while processing.
                // use SW.SHOWNA instead SW.SHOW to avoid some brief flashing when launched the window
                NativeMethods.ShowWindow(_messageHwnd.Handle, SW.SHOWNA);
                NativeMethods.SendMessage(_messageHwnd.Handle, WM.GETreplacedLEBARINFOEX, IntPtr.Zero, lParam);
                tbix = (replacedLEBARINFOEX)Marshal.PtrToStructure(lParam, typeof(replacedLEBARINFOEX));
            }
            finally
            {
                NativeMethods.ShowWindow(_messageHwnd.Handle, SW.HIDE);
                Utility.SafeFreeHGlobal(ref lParam);
            }

            // replacedLEBARINFOEX has information relative to the screen.  We need to convert the containing rect
            // to instead be relative to the top-right corner of the window.
            RECT rcAllCaptionButtons = RECT.Union(tbix.rgrect_CloseButton, tbix.rgrect_MinimizeButton);
            // For all known themes, the RECT for the maximize box shouldn't add anything to the union of the minimize and close boxes.
            replacedert.AreEqual(rcAllCaptionButtons, RECT.Union(rcAllCaptionButtons, tbix.rgrect_MaximizeButton));

            RECT rcWindow = NativeMethods.GetWindowRect(_messageHwnd.Handle);

            // Reorient the Top/Right to be relative to the top right edge of the Window.
            var deviceCaptionLocation = new Rect(
                rcAllCaptionButtons.Left - rcWindow.Width - rcWindow.Left,
                rcAllCaptionButtons.Top - rcWindow.Top,
                rcAllCaptionButtons.Width,
                rcAllCaptionButtons.Height);

            Rect logicalCaptionLocation = DpiHelper.DeviceRectToLogical(deviceCaptionLocation, SystemParameters2.DpiX / 96.0, SystemParameters2.Dpi / 96.0);

            WindowCaptionButtonsLocation = logicalCaptionLocation;
        }

19 View Source File : StructConverter.cs
License : GNU General Public License v3.0
Project Creator : berichan

public static byte[] ToBytes<T>(this T obj) where T : struct
        {
            int size = Marshal.SizeOf(obj);
            byte[] arr = new byte[size];

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

19 View Source File : StructConverter.cs
License : GNU General Public License v3.0
Project Creator : berichan

public static byte[] ToBytesClreplaced<T>(this T obj) where T : clreplaced
        {
            int size = Marshal.SizeOf(obj);
            byte[] arr = new byte[size];

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

19 View Source File : Program.cs
License : MIT License
Project Creator : bongiovimatthew-microsoft

static void MarshalFlow(string thumbprint)
        {
            //
            // Set up the data struct
            //
            NativeMethods.CERT_CREDENTIAL_INFO certInfo = new NativeMethods.CERT_CREDENTIAL_INFO();
            certInfo.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.CERT_CREDENTIAL_INFO));

            //
            // Locate the certificate in the certificate store 
            //
            X509Certificate2 certCredential = new X509Certificate2();
            X509Store userMyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            userMyStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certsReturned = userMyStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
            userMyStore.Close();

            if (certsReturned.Count == 0)
            {
                Console.WriteLine("Could not find the cert you want, aborting");
                return;
            }

            //
            // Marshal the certificate 
            //
            certCredential = certsReturned[0];
            certInfo.rgbHashOfCert = certCredential.GetCertHash();
            int size = Marshal.SizeOf(certInfo);
            IntPtr pCertInfo = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(certInfo, pCertInfo, false);
            IntPtr marshaledCredential = IntPtr.Zero;
            bool result = NativeMethods.CredMarshalCredential(NativeMethods.CRED_MARSHAL_TYPE.CertCredential, pCertInfo, out marshaledCredential);

            string certBlobForUsername = null;
            PSCredential psCreds = null;

            if (result)
            {
                certBlobForUsername = Marshal.PtrToStringUni(marshaledCredential);
                psCreds = new PSCredential(certBlobForUsername, new SecureString());
            }

            Marshal.FreeHGlobal(pCertInfo);
            if (marshaledCredential != IntPtr.Zero)
            {
                NativeMethods.CredFree(marshaledCredential);
            }
                
            Console.WriteLine("Certificate Credential Data: " + certBlobForUsername);
            CertFlow(certBlobForUsername);
        }

19 View Source File : DesignForm.cs
License : GNU Affero General Public License v3.0
Project Creator : bonimy

private void ProcessSizing(ref Message m)
        {
            var windowBounds = Marshal.PtrToStructure<WinApiRectangle>(m.LParam);

            var e = new RectangleEventArgs(windowBounds);
            OnAdjustWindowBounds(e);

            WinApiRectangle adjustedWindowBounds = e.Rectangle;

            Marshal.StructureToPtr(adjustedWindowBounds, m.LParam, false);
        }

19 View Source File : Struct.cs
License : GNU General Public License v3.0
Project Creator : BorjaMerino

public static byte[] GetBytes<T>(T obj) where T : struct {
            byte[] data = new byte[Marshal.SizeOf(obj)];
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

            try {
                Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
                return ConvertEndian<T>(data);
            } finally {
                handle.Free();
            }
        }

19 View Source File : PVMarshaler.cs
License : GNU General Public License v3.0
Project Creator : BRH-Media

public IntPtr MarshalManagedToNative(object managedObj)
        {

            MyProps t = MyProps.GetTop(m_Index);

            switch (t.GetStage())
            {
                case 0:
                {
                    // We are just starting a "Managed calling unmanaged"
                    // call.

                    // Cast the object back to a PropVariant and save it
                    // for use in MarshalNativeToManaged.
                    t.m_obj = managedObj as PropVariant;

                    // This could happen if (somehow) managedObj isn't a
                    // PropVariant.  During normal marshaling, the custom
                    // marshaler doesn't get called if the parameter is
                    // null.

                    // Release any memory currently allocated in the
                    // PropVariant.  In theory, the (managed) caller
                    // should have done this before making the call that
                    // got us here, but .Net programmers don't generally
                    // think that way.  To avoid any leaks, do it for them.
                    t.m_obj.Clear();

                    // Create an appropriately sized buffer (varies from
                    // x86 to x64).
                    int iSize = GetNativeDataSize();
                    t.m_ptr = t.Alloc(iSize);

                    // Copy in the (empty) PropVariant.  In theory we could
                    // just zero out the first 2 bytes (the VariantType),
                    // but since PropVariantClear wipes the whole struct,
                    // that's what we do here to be safe.
                    Marshal.StructureToPtr(t.m_obj, t.m_ptr, false);

                    break;
                }
                case 1:
                {
                    if (!System.Object.ReferenceEquals(t.m_obj, managedObj))
                    {
                        // If we get here, we have already received a call
                        // to MarshalNativeToManaged where we created a
                        // PropVariant and stored it into t.m_obj.  But
                        // the object we just got preplaceded here isn't the
                        // same one.  Therefore instead of being the second
                        // half of an "Unmanaged calling managed" (as
                        // m_InProcsss led us to believe), this is really
                        // the first half of a nested "Managed calling
                        // unmanaged" (see Recursion in the comments at the
                        // top of this clreplaced).  Add another layer.
                        MyProps.AddLayer(m_Index);

                        // Try this call again now that we have fixed
                        // m_CurrentProps.
                        return MarshalManagedToNative(managedObj);
                    }

                    // This is (probably) the second half of "Unmanaged
                    // calling managed."  However, it could be the first
                    // half of a nested usage of PropVariants.  If it is a
                    // nested, we'll eventually figure that out in case 2.

                    // Copy the data from the managed object into the
                    // native pointer that we received in
                    // MarshalNativeToManaged.
                    Marshal.StructureToPtr(t.m_obj, t.m_ptr, false);

                    break;
                }
                case 2:
                {
                    // Apparently this is 'part 3' of a 2 part call.  Which
                    // means we are doing a nested call.  Normally we would
                    // catch the fact that this is a nested call with the
                    // ReferenceEquals check above.  However, if the same
                    // PropVariant instance is being preplaceded thru again, we
                    // end up here.
                    // So, add a layer.
                    MyProps.SplitLayer(m_Index);

                    // Try this call again now that we have fixed
                    // m_CurrentProps.
                    return MarshalManagedToNative(managedObj);
                }
                default:
                {
                    Environment.FailFast("Something horrible has " +
                                         "happened, probaby due to " +
                                         "marshaling of nested " +
                                         "PropVariant calls.");
                    break;
                }
            }
            t.StageComplete();

            return t.m_ptr;
        }

19 View Source File : WlanApi.cs
License : MIT License
Project Creator : buscseik

public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
			{
				IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
				Marshal.StructureToPtr(ssid, ssidPtr, false);
				try
				{
					IntPtr bssListPtr;
					Wlan.ThrowIfError(
						Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
					try
					{
						return ConvertBssListPtr(bssListPtr);
					}
					finally
					{
						Wlan.WlanFreeMemory(bssListPtr);
					}
				}
				finally
				{
					Marshal.FreeHGlobal(ssidPtr);
				}
			}

19 View Source File : WlanApi.cs
License : MIT License
Project Creator : buscseik

public void Connect(string Bssid, string Ssid, string Pwd)
            {
                byte[] desBssid = Bssid.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();

                Wlan.NDIS_OBJECT_HEADER ndoh;
                ndoh.Type = Wlan.NDIS_OBJECT_TYPE_DEFAULT;
                ndoh.Revision = Wlan.DOT11_BSSID_LIST_REVISION_1;
                ndoh.Size = (ushort)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Wlan.DOT11_BSSID_LIST));

                Wlan.DOT11_BSSID_LIST desBssidList = new Wlan.DOT11_BSSID_LIST();
                desBssidList.Header = ndoh;
                desBssidList.uNumOfEntries = 1;
                desBssidList.uTotalNumOfEntries = 1;
                Wlan.DOT11_MAC_ADDRESS bssid = new Wlan.DOT11_MAC_ADDRESS();
                bssid.Dot11MacAddress = desBssid;
                desBssidList.BSSIDs = new Wlan.DOT11_MAC_ADDRESS[1];
                desBssidList.BSSIDs[0] = bssid;

                IntPtr desBssidListPtr = Marshal.AllocHGlobal(Marshal.SizeOf(desBssidList));
                Marshal.StructureToPtr(desBssidList, desBssidListPtr, false);


                Wlan.DOT11_SSID dot11Ssid = new Wlan.DOT11_SSID();
                dot11Ssid.ucSSID =  Ssid; 
                dot11Ssid.uSSIDLength = (uint)dot11Ssid.ucSSID.Length;

                IntPtr dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dot11Ssid));
                Marshal.StructureToPtr(dot11Ssid, dot11SsidPtr, false);
                                
                string profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>preplacedPhrase</keyType><protected>false</protected><keyMaterial>{1}</keyMaterial></sharedKey></security></MSM></WLANProfile>", Ssid, Pwd);
                SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);

                Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
                connectionParams.wlanConnectionMode = Wlan.WlanConnectionMode.Profile;
                connectionParams.profile = Ssid;
                connectionParams.dot11SsidPtr = dot11SsidPtr;
                connectionParams.dot11BssType = Wlan.Dot11BssType.Any;
                connectionParams.flags = 0;
                connectionParams.desiredBssidListPtr = desBssidListPtr;
                Connect(connectionParams);

            }

19 View Source File : WlanApi.cs
License : MIT License
Project Creator : buscseik

public void Connect(string Bssid, string ProfileName)
            {
                byte[] desBssid = Bssid.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();

                Wlan.NDIS_OBJECT_HEADER ndoh;
                ndoh.Type = Wlan.NDIS_OBJECT_TYPE_DEFAULT;
                ndoh.Revision = Wlan.DOT11_BSSID_LIST_REVISION_1;
                ndoh.Size = (ushort)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Wlan.DOT11_BSSID_LIST));

                Wlan.DOT11_BSSID_LIST desBssidList = new Wlan.DOT11_BSSID_LIST();
                desBssidList.Header = ndoh;
                desBssidList.uNumOfEntries = 1;
                desBssidList.uTotalNumOfEntries = 1;
                Wlan.DOT11_MAC_ADDRESS bssid = new Wlan.DOT11_MAC_ADDRESS();
                bssid.Dot11MacAddress = desBssid;
                desBssidList.BSSIDs = new Wlan.DOT11_MAC_ADDRESS[1];
                desBssidList.BSSIDs[0] = bssid;

                IntPtr desBssidListPtr = Marshal.AllocHGlobal(Marshal.SizeOf(desBssidList));
                Marshal.StructureToPtr(desBssidList, desBssidListPtr, false);


                Wlan.DOT11_SSID dot11Ssid = new Wlan.DOT11_SSID();
                dot11Ssid.ucSSID = ProfileName;
                dot11Ssid.uSSIDLength = (uint)dot11Ssid.ucSSID.Length;

                IntPtr dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dot11Ssid));
                Marshal.StructureToPtr(dot11Ssid, dot11SsidPtr, false);

                string profileXml = GetProfileXml(ProfileName);
                
                SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);

                Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
                connectionParams.wlanConnectionMode = Wlan.WlanConnectionMode.Profile;
                connectionParams.profile = ProfileName;
                connectionParams.dot11SsidPtr = dot11SsidPtr;
                connectionParams.dot11BssType = Wlan.Dot11BssType.Any;
                connectionParams.flags = 0;
                connectionParams.desiredBssidListPtr = desBssidListPtr;
                Connect(connectionParams);
            }

19 View Source File : WlanApi.cs
License : MIT License
Project Creator : buscseik

public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
			{
				Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
				connectionParams.wlanConnectionMode = connectionMode;
				connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
				Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
				connectionParams.dot11BssType = bssType;
				connectionParams.flags = flags;
				Connect(connectionParams);
				Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
				Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
			}

19 View Source File : WindowHelper.cs
License : Apache License 2.0
Project Creator : cairoshell

public static void SetWindowBlur(IntPtr hWnd, bool enable)
        {
            if (EnvironmentHelper.IsWindows10OrBetter)
            {
                // https://github.com/riverar/sample-win32-acrylicblur
                // License: MIT
                var accent = new AccentPolicy();
                var accentStructSize = Marshal.SizeOf(accent);
                if (enable)
                {
                    if (EnvironmentHelper.IsWindows10RS4OrBetter)
                    {
                        accent.AccentState = AccentState.ACCENT_ENABLE_ACRYLICBLURBEHIND;
                        accent.GradientColor = (0 << 24) | (0xFFFFFF /* BGR */ & 0xFFFFFF);
                    }
                    else
                    {
                        accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;
                    }
                }
                else
                {
                    accent.AccentState = AccentState.ACCENT_DISABLED;
                }

                var accentPtr = Marshal.AllocHGlobal(accentStructSize);
                Marshal.StructureToPtr(accent, accentPtr, false);

                var data = new WindowCompositionAttributeData();
                data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
                data.SizeOfData = accentStructSize;
                data.Data = accentPtr;

                SetWindowCompositionAttribute(hWnd, ref data);

                Marshal.FreeHGlobal(accentPtr);
            }
        }

19 View Source File : TasksService.cs
License : Apache License 2.0
Project Creator : cairoshell

private void ShellWinProc(Message msg)
        {
            if (msg.Msg == WM_SHELLHOOKMESSAGE)
            {
                try
                {
                    lock (_windowsLock)
                    {
                        switch ((HSHELL)msg.WParam.ToInt32())
                        {
                            case HSHELL.WINDOWCREATED:
                                ShellLogger.Debug("TasksService: Created: " + msg.LParam);
                                if (!Windows.Any(i => i.Handle == msg.LParam))
                                {
                                    addWindow(msg.LParam);
                                }
                                else
                                {
                                    ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                    win.UpdateProperties();
                                }
                                break;

                            case HSHELL.WINDOWDESTROYED:
                                ShellLogger.Debug("TasksService: Destroyed: " + msg.LParam);
                                removeWindow(msg.LParam);
                                break;

                            case HSHELL.WINDOWREPLACING:
                                ShellLogger.Debug("TasksService: Replacing: " + msg.LParam);
                                if (Windows.Any(i => i.Handle == msg.LParam))
                                {
                                    ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                    win.State = ApplicationWindow.WindowState.Inactive;
                                    win.SetShowInTaskbar();
                                }
                                else
                                {
                                    addWindow(msg.LParam);
                                }
                                break;
                            case HSHELL.WINDOWREPLACED:
                                ShellLogger.Debug("TasksService: Replaced: " + msg.LParam);
                                // TODO: If a window gets replaced, we lose app-level state such as overlay icons.
                                removeWindow(msg.LParam);
                                break;

                            case HSHELL.WINDOWACTIVATED:
                            case HSHELL.RUDEAPPACTIVATED:
                                ShellLogger.Debug("TasksService: Activated: " + msg.LParam);

                                foreach (var aWin in Windows.Where(w => w.State == ApplicationWindow.WindowState.Active))
                                {
                                    aWin.State = ApplicationWindow.WindowState.Inactive;
                                }

                                if (msg.LParam != IntPtr.Zero)
                                {
                                    ApplicationWindow win = null;

                                    if (Windows.Any(i => i.Handle == msg.LParam))
                                    {
                                        win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                        win.State = ApplicationWindow.WindowState.Active;
                                        win.SetShowInTaskbar();
                                    }
                                    else
                                    {
                                        win = addWindow(msg.LParam, ApplicationWindow.WindowState.Active);
                                    }

                                    if (win != null)
                                    {
                                        foreach (ApplicationWindow wind in Windows)
                                        {
                                            if (wind.WinFileName == win.WinFileName && wind.Handle != win.Handle)
                                                wind.SetShowInTaskbar();
                                        }
                                    }
                                }
                                break;

                            case HSHELL.FLASH:
                                ShellLogger.Debug("TasksService: Flashing window: " + msg.LParam);
                                if (Windows.Any(i => i.Handle == msg.LParam))
                                {
                                    ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                    
                                    if (win.State != ApplicationWindow.WindowState.Active)
                                    {
                                        win.State = ApplicationWindow.WindowState.Flashing;
                                    }

                                    redrawWindow(win);
                                }
                                else
                                {
                                    addWindow(msg.LParam, ApplicationWindow.WindowState.Flashing, true);
                                }
                                break;

                            case HSHELL.ACTIVATESHELLWINDOW:
                                ShellLogger.Debug("TasksService: Activate shell window called.");
                                break;

                            case HSHELL.ENDTASK:
                                ShellLogger.Debug("TasksService: EndTask called: " + msg.LParam);
                                removeWindow(msg.LParam);
                                break;

                            case HSHELL.GETMINRECT:
                                ShellLogger.Debug("TasksService: GetMinRect called: " + msg.LParam);
                                SHELLHOOKINFO winHandle = (SHELLHOOKINFO)Marshal.PtrToStructure(msg.LParam, typeof(SHELLHOOKINFO));
                                winHandle.rc = new NativeMethods.Rect { Bottom = 100, Left = 0, Right = 100, Top = 0 };
                                Marshal.StructureToPtr(winHandle, msg.LParam, true);
                                msg.Result = winHandle.hwnd;
                                return; // return here so the result isnt reset to DefWindowProc

                            case HSHELL.REDRAW:
                                ShellLogger.Debug("TasksService: Redraw called: " + msg.LParam);
                                if (Windows.Any(i => i.Handle == msg.LParam))
                                {
                                    ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);

                                    if (win.State == ApplicationWindow.WindowState.Flashing)
                                    {
                                        win.State = ApplicationWindow.WindowState.Inactive;
                                    }

                                    redrawWindow(win);
                                }
                                else
                                {
                                    addWindow(msg.LParam, ApplicationWindow.WindowState.Inactive, true);
                                }
                                break;

                            // TaskMan needs to return true if we provide our own task manager to prevent explorers.
                            // case HSHELL.TASKMAN:
                            //     SingletonLogger.Instance.Info("TaskMan Message received.");
                            //     break;

                            default:
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShellLogger.Error("TasksService: Error in ShellWinProc. ", ex);
                    Debugger.Break();
                }
            }
            else if (msg.Msg == WM_TASKBARCREATEDMESSAGE)
            {
                ShellLogger.Debug("TasksService: TaskbarCreated received, setting ITaskbarList window");
                setTaskbarListHwnd(_HookWin.Handle);
            }
            else
            {
                // Handle ITaskbarList functions, most not implemented yet

                ApplicationWindow win = null;

                switch (msg.Msg)
                {
                    case (int)WM.USER + 50:
                        // ActivateTab
                        // Also sends WM_SHELLHOOK message
                        ShellLogger.Debug("TasksService: ITaskbarList: ActivateTab HWND:" + msg.LParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 60:
                        // MarkFullscreenWindow
                        ShellLogger.Debug("TasksService: ITaskbarList: MarkFullscreenWindow HWND:" + msg.LParam + " Entering? " + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 64:
                        // SetProgressValue
                        ShellLogger.Debug("TasksService: ITaskbarList: SetProgressValue HWND:" + msg.WParam + " Progress: " + msg.LParam);

                        win = new ApplicationWindow(this, msg.WParam);
                        if (Windows.Contains(win))
                        {
                            win = Windows.First(wnd => wnd.Handle == msg.WParam);
                            win.ProgressValue = (int)msg.LParam;
                        }

                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 65:
                        // SetProgressState
                        ShellLogger.Debug("TasksService: ITaskbarList: SetProgressState HWND:" + msg.WParam + " Flags: " + msg.LParam);

                        win = new ApplicationWindow(this, msg.WParam);
                        if (Windows.Contains(win))
                        {
                            win = Windows.First(wnd => wnd.Handle == msg.WParam);
                            win.ProgressState = (TBPFLAG)msg.LParam;
                        }

                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 67:
                        // RegisterTab
                        ShellLogger.Debug("TasksService: ITaskbarList: RegisterTab MDI HWND:" + msg.LParam + " Tab HWND: " + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 68:
                        // UnregisterTab
                        ShellLogger.Debug("TasksService: ITaskbarList: UnregisterTab Tab HWND: " + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 71:
                        // SetTabOrder
                        ShellLogger.Debug("TasksService: ITaskbarList: SetTabOrder HWND:" + msg.WParam + " Before HWND: " + msg.LParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 72:
                        // SetTabActive
                        ShellLogger.Debug("TasksService: ITaskbarList: SetTabActive HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 75:
                        // Unknown
                        ShellLogger.Debug("TasksService: ITaskbarList: Unknown HWND:" + msg.WParam + " LParam: " + msg.LParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 76:
                        // ThumbBarAddButtons
                        ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarAddButtons HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 77:
                        // ThumbBarUpdateButtons
                        ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarUpdateButtons HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 78:
                        // ThumbBarSetImageList
                        ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarSetImageList HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 79:
                        // SetOverlayIcon - Icon
                        ShellLogger.Debug("TasksService: ITaskbarList: SetOverlayIcon - Icon HWND:" + msg.WParam);

                        win = new ApplicationWindow(this, msg.WParam);
                        if (Windows.Contains(win))
                        {
                            win = Windows.First(wnd => wnd.Handle == msg.WParam);
                            win.SetOverlayIcon(msg.LParam);
                        }

                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 80:
                        // SetThumbnailTooltip
                        ShellLogger.Debug("TasksService: ITaskbarList: SetThumbnailTooltip HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 81:
                        // SetThumbnailClip
                        ShellLogger.Debug("TasksService: ITaskbarList: SetThumbnailClip HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 85:
                        // SetOverlayIcon - Description
                        ShellLogger.Debug("TasksService: ITaskbarList: SetOverlayIcon - Description HWND:" + msg.WParam);

                        win = new ApplicationWindow(this, msg.WParam);
                        if (Windows.Contains(win))
                        {
                            win = Windows.First(wnd => wnd.Handle == msg.WParam);
                            win.SetOverlayIconDescription(msg.LParam);
                        }

                        msg.Result = IntPtr.Zero;
                        return;
                    case (int)WM.USER + 87:
                        // SetTabProperties
                        ShellLogger.Debug("TasksService: ITaskbarList: SetTabProperties HWND:" + msg.WParam);
                        msg.Result = IntPtr.Zero;
                        return;
                }
            }

            msg.Result = DefWindowProc(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);
        }

19 View Source File : TrayService.cs
License : Apache License 2.0
Project Creator : cairoshell

private IntPtr AppBarMessageAction(APPBARMSGDATAV3 amd, ref bool handled)
        {
            // only handle certain messages, send other AppBar messages to default handler
            switch ((ABMsg)amd.dwMessage)
            {
                case ABMsg.ABM_GETTASKBARPOS:
                    IntPtr hShared = SHLockShared((IntPtr)amd.hSharedMemory, (uint)amd.dwSourceProcessId);
                    APPBARDATAV2 abd = (APPBARDATAV2)Marshal.PtrToStructure(hShared, typeof(APPBARDATAV2));
                    FillTrayHostSizeData(ref abd);
                    Marshal.StructureToPtr(abd, hShared, false);
                    SHUnlockShared(hShared);
                    handled = true;
                    return (IntPtr)1;
                case ABMsg.ABM_GETSTATE:
                    if (autoHideBarDelegate == null)
                    {
                        break;
                    }

                    handled = true;

                    if (autoHideBarDelegate(null) != IntPtr.Zero)
                    {
                        return (IntPtr)ABState.AutoHide;
                    }

                    return (IntPtr)ABState.Default;
                case ABMsg.ABM_GETAUTOHIDEBAR:
                    if (autoHideBarDelegate == null)
                    {
                        break;
                    }

                    handled = true;
                    return autoHideBarDelegate((ABEdge)amd.abd.uEdge);
            }
            return IntPtr.Zero;
        }

19 View Source File : TasksService.cs
License : Apache License 2.0
Project Creator : cairoshell

private void SetMinimizedMetrics()
        {
            MinimizedMetrics mm = new MinimizedMetrics
            {
                cbSize = (uint)Marshal.SizeOf(typeof(MinimizedMetrics))
            };

            IntPtr mmPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MinimizedMetrics)));

            try
            {
                Marshal.StructureToPtr(mm, mmPtr, true);
                SystemParametersInfo(SPI.GETMINIMIZEDMETRICS, mm.cbSize, mmPtr, SPIF.None);
                mm.iWidth = 140;
                mm.iArrange |= MinimizedMetricsArrangement.Hide;
                Marshal.StructureToPtr(mm, mmPtr, true);
                SystemParametersInfo(SPI.SETMINIMIZEDMETRICS, mm.cbSize, mmPtr, SPIF.None);
            }
            finally
            {
                Marshal.DestroyStructure(mmPtr, typeof(MinimizedMetrics));
                Marshal.FreeHGlobal(mmPtr);
            }
        }

19 View Source File : ChromelyHost.cs
License : MIT License
Project Creator : chromelyapps

protected override IntPtr WndProc(IntPtr hWnd, uint message, IntPtr wParam, IntPtr lParam)
        {
            WM msg = (WM)message;
            if (!_windowFrameless)
            {
                return base.WndProc(hWnd, message, wParam, lParam);
            }

            switch (msg)
            {
                case WM.CREATE:
                    _handle = hWnd;
                    break;
                case WM.NCPAINT:
                    return IntPtr.Zero;
                case WM.NCACTIVATE:
                    return DefWindowProcW(hWnd, msg, wParam, new IntPtr(-1));
                case WM.SIZE:
                    {
                        _maximized = wParam == (IntPtr)WINDOW_SIZE.MAXIMIZED
                            || wParam == (IntPtr)WINDOW_SIZE.MAXSHOW;
                        ForceRedraw(hWnd);
                        break;
                    }
                case WM.NCCALCSIZE:
                    {
                        var captionHeight = GetSystemMetrics(SystemMetric.SM_CYCAPTION);
                        var menuHeight = GetSystemMetrics(SystemMetric.SM_CYMENU);
                        var padderBorder = GetSystemMetrics(SystemMetric.SM_CXPADDEDBORDER);
                        // NB: 'menuHeight' substraction probably may broke it if window will have a replacedle in a caption.
                        var topFrameHeight = captionHeight - menuHeight + padderBorder;

                        var result = DefWindowProcW(hWnd, msg, wParam, lParam);
                        var csp = (NcCalcSizeParams)Marshal.PtrToStructure(lParam, typeof(NcCalcSizeParams));
                        csp.Region.Input.TargetWindowRect.top -= _maximized ? 0 : topFrameHeight;
                        Marshal.StructureToPtr(csp, lParam, false);
                        return result;
                    }
                case WM.NCHITTEST:
                    {
                        var result = DefWindowProcW(hWnd, msg, wParam, lParam);
                        if (BorderHitTestResults.Contains((HT)result))
                        {
                            return result;
                        }

                        // TODO: Try to find out why this is not enough for drag window functionality.
                        return (IntPtr)HT.CAPTION;
                    }
            }

            return base.WndProc(hWnd, message, wParam, lParam);
        }

19 View Source File : Scene.cs
License : GNU General Public License v3.0
Project Creator : CircuitLord

public static IntPtr GetSteamAudioMaterialBuffer(Transform obj)
        {
            var material = new Material();
            var found = false;

            var currentObject = obj;
            while (currentObject != null) {
                var steamAudioMaterial = currentObject.GetComponent<SteamAudioMaterial>();
                if (steamAudioMaterial != null) {
                    material = CopyMaterial(steamAudioMaterial.Value);
                    found = true;
                    break;
                }
                currentObject = currentObject.parent;
            }

            if (!found) {
                var steamAudioManager = GameObject.FindObjectOfType<SteamAudioManager>();
                if (steamAudioManager == null) {
                    return IntPtr.Zero;
                }
                material = CopyMaterial(steamAudioManager.materialValue);
            }

            Marshal.StructureToPtr(material, materialBuffer, true);
            return materialBuffer;
        }

19 View Source File : DmoMediaType.cs
License : GNU General Public License v3.0
Project Creator : ciribob

public void SetWaveFormat(WaveFormat waveFormat)
        {
            majortype = MediaTypes.MEDIATYPE_Audio;

            var wfe = waveFormat as WaveFormatExtensible;
            if (wfe != null)
            {
                subtype = wfe.SubFormat;
            }
            else
            {
                switch (waveFormat.Encoding)
                {
                    case WaveFormatEncoding.Pcm:
                        subtype = AudioMediaSubtypes.MEDIASUBTYPE_PCM;
                        break;
                    case WaveFormatEncoding.IeeeFloat:
                        subtype = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
                        break;
                    case WaveFormatEncoding.MpegLayer3:
                        subtype = AudioMediaSubtypes.WMMEDIASUBTYPE_MP3;
                        break;
                    default:
                        throw new ArgumentException($"Not a supported encoding {waveFormat.Encoding}");
                }
            }
            bFixedSizeSamples = SubType == AudioMediaSubtypes.MEDIASUBTYPE_PCM ||
                                SubType == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
            formattype = DmoMediaTypeGuids.FORMAT_WaveFormatEx;
            if (cbFormat < Marshal.SizeOf(waveFormat))
                throw new InvalidOperationException("Not enough memory replacedigned for a WaveFormat structure");
            //Debug.replacedert(cbFormat >= ,"Not enough space");
            Marshal.StructureToPtr(waveFormat, pbFormat, false);
        }

See More Examples