System.Runtime.InteropServices.Marshal.PtrToStructure(System.IntPtr, System.Type)

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

1093 Examples 7

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

public object GetLParam(Type cls)
            => Marshal.PtrToStructure(LParam, cls);

19 View Source File : AreaForm.cs
License : MIT License
Project Creator : 1CM69

public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
            {
                var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
                var iconImage = IntPtr.Zero;
                var cursorHandle = IntPtr.Zero;

                try
                {
                    var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));

                    if (imageIndex >= header.count)
                        throw new ArgumentOutOfRangeException("imageIndex");

                    var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
                    var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));

                    iconImage = Marshal.AllocHGlobal(info.size + 4);
                    Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
                    Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
                    Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);

                    cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
                    return new Cursor(cursorHandle);
                }
                finally
                {
                    if (cursorHandle != IntPtr.Zero)
                        NativeMethods.DestroyIcon(cursorHandle);

                    if (iconImage != IntPtr.Zero)
                        Marshal.FreeHGlobal(iconImage);

                    if (resourceHandle.IsAllocated)
                        resourceHandle.Free();
                }
            }

19 View Source File : WaveFormat.cs
License : MIT License
Project Creator : 3wz

public static WaveFormat MarshalFromPtr(IntPtr pointer)
        {
            WaveFormat waveFormat = (WaveFormat)Marshal.PtrToStructure(pointer, typeof(WaveFormat));
            switch (waveFormat.Encoding)
            {
                case WaveFormatEncoding.Pcm:
                    // can't rely on extra size even being there for PCM so blank it to avoid reading
                    // corrupt data
                    waveFormat.extraSize = 0;
                    break;
                case WaveFormatEncoding.Extensible:
                    waveFormat = (WaveFormatExtensible)Marshal.PtrToStructure(pointer, typeof(WaveFormatExtensible));
                    break;
                case WaveFormatEncoding.Adpcm:
                    waveFormat = (AdpcmWaveFormat)Marshal.PtrToStructure(pointer, typeof(AdpcmWaveFormat));
                    break;
                case WaveFormatEncoding.Gsm610:
                    waveFormat = (Gsm610WaveFormat)Marshal.PtrToStructure(pointer, typeof(Gsm610WaveFormat));
                    break;
                default:
                    if (waveFormat.ExtraSize > 0)
                    {
                        waveFormat = (WaveFormatExtraData)Marshal.PtrToStructure(pointer, typeof(WaveFormatExtraData));
                    }
                    break;
            }
            return waveFormat;            
        }

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 : DellSmbiosBzh.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static bool RemoveDriver()
        {
            IntPtr serviceManagerHandle;
            IntPtr serviceHandle;
            bool result;

            StopDriver();

            serviceManagerHandle = ServiceMethods.OpenSCManager(null, null, ServiceAccess.ServiceManagerAllAccess);

            if (serviceManagerHandle == IntPtr.Zero)
            {
                return false;
            }

            serviceHandle = ServiceMethods.OpenService(serviceManagerHandle, DriverName, ServiceAccess.AllAccess);
            ServiceMethods.CloseServiceHandle(serviceManagerHandle);

            if (serviceManagerHandle == IntPtr.Zero)
            {
                return false;
            }

            result = ServiceMethods.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out int bytesNeeded);

            if ((ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.InsufficientBuffer)
            {
                IntPtr serviceConfigurationPtr = Marshal.AllocHGlobal(bytesNeeded);

                result = ServiceMethods.QueryServiceConfig(serviceHandle, serviceConfigurationPtr, bytesNeeded, out _);
                QueryServiceConfig serviceConfiguration = (QueryServiceConfig) Marshal.PtrToStructure(serviceConfigurationPtr, typeof(QueryServiceConfig));

                if (!result)
                {
                    Marshal.FreeHGlobal(serviceConfigurationPtr);
                    ServiceMethods.CloseServiceHandle(serviceHandle);
                    return result;
                }

                // If service is set to load automatically, don't delete it!
                if (serviceConfigurationPtr != IntPtr.Zero && serviceConfiguration.startType == ServiceStartType.DemandStart)
                {
                    result = ServiceMethods.DeleteService(serviceHandle);
                }

                Marshal.FreeHGlobal(serviceConfigurationPtr);
            }

            ServiceMethods.CloseServiceHandle(serviceHandle);

            return result;
        }

19 View Source File : OpenVRRenderModel.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
        {
            var pRenderModel = System.IntPtr.Zero;

            EVRRenderModelError error;
            while (true)
            {
                error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
                if (error != EVRRenderModelError.Loading)
                    break;

                Sleep();
            }

            if (error != EVRRenderModelError.None)
            {
                Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
                return null;
            }

            var renderModel = MarshalRenderModel(pRenderModel);

            var vertices = new Vector3[renderModel.unVertexCount];
            var normals = new Vector3[renderModel.unVertexCount];
            var uv = new Vector2[renderModel.unVertexCount];

            var type = typeof(RenderModel_Vertex_t);
            for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
            {
                var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
                var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

                vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
                normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
                uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
            }

            int indexCount = (int)renderModel.unTriangleCount * 3;
            var indices = new short[indexCount];
            Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

            var triangles = new int[indexCount];
            for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
            {
                triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
                triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
                triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
            }

            var mesh = new Mesh
            {
                vertices = vertices,
                normals = normals,
                uv = uv,
                triangles = triangles
            };

            // Check cache before loading texture.
            var material = materials[renderModel.diffuseTextureId] as Material;
            if (material == null || material.mainTexture == null)
            {
                var pDiffuseTexture = System.IntPtr.Zero;

                while (true)
                {
                    error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                    if (error != EVRRenderModelError.Loading)
                    {
                        break;
                    }

                    Sleep();
                }

                if (error == EVRRenderModelError.None)
                {
                    var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
                    var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
                    if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
                    {
                        texture.Apply();
                        System.IntPtr texturePointer = texture.GetNativeTexturePtr();
                        while (true)
                        {
                            error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
                            if (error != EVRRenderModelError.Loading)
                            {
                                break;
                            }

                            Sleep();
                        }
                    }
                    else
                    {
                        var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
                        Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                        var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                        int iColor = 0;
                        for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                        {
                            for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                            {
                                var r = textureMapData[iColor++];
                                var g = textureMapData[iColor++];
                                var b = textureMapData[iColor++];
                                var a = textureMapData[iColor++];
                                colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                            }
                        }

                        texture.SetPixels32(colors);
                        texture.Apply();
                    }

                    material = new Material(shader != null ? shader : Shader.Find("Mixed Reality Toolkit/Standard"))
                    {
                        mainTexture = texture
                    };

                    materials[renderModel.diffuseTextureId] = material;

                    renderModels.FreeTexture(pDiffuseTexture);
                }
                else
                {
                    Debug.Log("Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
                }
            }

            // Delay freeing when we can since we'll often get multiple requests for the same model right
            // after another (e.g. two controllers or two base stations).
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                renderModels.FreeRenderModel(pRenderModel);
            }
            else
#endif
            {
                StartCoroutine(FreeRenderModel(pRenderModel));
            }

            return new RenderModel(mesh, material);
        }

19 View Source File : OpenVRRenderModel.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private RenderModel_t MarshalRenderModel(System.IntPtr pRenderModel)
        {
#if !ENABLE_DOTNET
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t_Packed));
                RenderModel_t model = new RenderModel_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
#endif
            {
                return (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
            }
        }

19 View Source File : OpenVRRenderModel.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private RenderModel_TextureMap_t MarshalRenderModel_TextureMap(System.IntPtr pRenderModel)
        {
#if !ENABLE_DOTNET
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_TextureMap_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t_Packed));
                RenderModel_TextureMap_t model = new RenderModel_TextureMap_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
#endif
            {
                return (RenderModel_TextureMap_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t));
            }
        }

19 View Source File : OvrAvatarAssetMesh.cs
License : MIT License
Project Creator : absurd-joy

private void LoadBlendShapes(IntPtr replacedet, long vertexCount)
    {
        UInt32 blendShapeCount = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeCount(replacedet);
        IntPtr blendShapeVerts = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeVertices(replacedet);

        AvatarLogger.Log("LoadBlendShapes: " + blendShapeCount);

        if (blendShapeVerts != IntPtr.Zero)
        {
            long offset = 0;
            long blendVertexSize = (long)Marshal.SizeOf(typeof(ovrAvatarBlendVertex));
            long blendVertexBufferStart = blendShapeVerts.ToInt64();

            for (UInt32 blendIndex = 0; blendIndex < blendShapeCount; blendIndex++)
            {
                Vector3[] blendVerts = new Vector3[vertexCount];
                Vector3[] blendNormals = new Vector3[vertexCount];
                Vector3[] blendTangents = new Vector3[vertexCount];

                for (long i = 0; i < vertexCount; i++)
                {
                    ovrAvatarBlendVertex vertex = (ovrAvatarBlendVertex)Marshal.PtrToStructure(new IntPtr(blendVertexBufferStart + offset), typeof(ovrAvatarBlendVertex));
                    blendVerts[i] = new Vector3(vertex.x, vertex.y, -vertex.z);
                    blendNormals[i] = new Vector3(vertex.nx, vertex.ny, -vertex.nz);
                    blendTangents[i] = new Vector4(vertex.tx, vertex.ty, -vertex.tz);

                    offset += blendVertexSize;
                }

                IntPtr namePtr = CAPI.ovrAvatarreplacedet_GetMeshBlendShapeName(replacedet, blendIndex);
                string name = Marshal.PtrToStringAnsi(namePtr);
                const float frameWeight = 100f;
                mesh.AddBlendShapeFrame(name, frameWeight, blendVerts, blendNormals, blendTangents);
            }
        }
    }

19 View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy

public static FrameHeader FromBytes(byte[] arr)
		{
			FrameHeader header = new FrameHeader();

			int size = Marshal.SizeOf(header);
			Trace.replacedert(size == StructSize);

			IntPtr ptr = Marshal.AllocHGlobal(size);

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

			header = (FrameHeader)Marshal.PtrToStructure(ptr, header.GetType());
			Marshal.FreeHGlobal(ptr);

			return header;
		}

19 View Source File : PowerManager.cs
License : MIT License
Project Creator : ABTSoftware

private Guid GetActiveGuid()
        {
            Guid ActiveScheme = Guid.Empty;
            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
            if (PowerGetActiveScheme((IntPtr)null, out ptr) == 0)
            {
                ActiveScheme = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid));
                if (ptr != null)
                {
                    Marshal.FreeHGlobal(ptr);
                }
            }
            return ActiveScheme;
        }

19 View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit

private static string GetNameFromHandle(SafeGenericHandle handle)
        {
            uint length;

            NativeMethods.NtQueryObject(
                handle,
                OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
                IntPtr.Zero, 0, out length);
            IntPtr ptr = IntPtr.Zero;
            try
            {
                try { }
                finally
                {
                    ptr = Marshal.AllocHGlobal((int)length);
                }

                if (NativeMethods.NtQueryObject(
                    handle,
                    OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
                    ptr, length, out length) != NTSTATUS.STATUS_SUCCESS)
                {
                    return null;
                }

                var unicodeStringName = (UNICODE_STRING)Marshal.PtrToStructure(ptr, typeof(UNICODE_STRING));
                return unicodeStringName.ToString();
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }

19 View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit

private static string GetTypeFromHandle(SafeGenericHandle handle)
        {
            uint length;
            NativeMethods.NtQueryObject(handle,
                OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
                IntPtr.Zero,
                0,
                out length);

            IntPtr ptr = IntPtr.Zero;
            try
            {
                try
                {
                }
                finally
                {
                    ptr = Marshal.AllocHGlobal((int)length);
                }

                if (NativeMethods.NtQueryObject(handle,
                    OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
                    ptr,
                    length,
                    out length) != NTSTATUS.STATUS_SUCCESS)
                {
                    return null;
                }

                var typeInformation =
                    (PUBLIC_OBJECT_TYPE_INFORMATION)
                        Marshal.PtrToStructure(ptr, typeof(PUBLIC_OBJECT_TYPE_INFORMATION));
                return typeInformation.TypeName.ToString();
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }

19 View Source File : SystemUtility.cs
License : MIT License
Project Creator : action-bi-toolkit

public static IEnumerable<FileHandle> GetHandles(int[] processIds)
        {
            var longProcIds = processIds.Select(Convert.ToUInt64).OrderBy(x => x).ToArray();
            uint length = 0x10000;
            IntPtr ptr = IntPtr.Zero;
            try
            {
                try { }
                finally
                {
                    ptr = Marshal.AllocHGlobal((int)length);
                }


                uint returnLength;
                NTSTATUS result;
                while ((result = NativeMethods.NtQuerySystemInformation(
                    SYSTEM_INFORMATION_CLreplaced.SystemHandleInformation, ptr, length, out returnLength)) ==
                       NTSTATUS.STATUS_INFO_LENGTH_MISMATCH)
                {
                    length = ((returnLength + 0xffff) & ~(uint)0xffff);
                    try { }
                    finally
                    {
                        Marshal.FreeHGlobal(ptr);
                        ptr = Marshal.AllocHGlobal((int)length);
                    }
                }

                if (result != NTSTATUS.STATUS_SUCCESS)
                    yield break;

                long handleCount = Marshal.ReadInt64(ptr);
                int offset = sizeof(long) + sizeof(long);
                int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
                for (int i = 0; i < handleCount; i++)
                {
                    var handleEntry =
                        (SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX)Marshal.PtrToStructure(
                        IntPtr.Add(ptr, offset), typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));

                    if (Array.BinarySearch(longProcIds, handleEntry.UniqueProcessId) > -1 
                        && FileHandle.TryCreate(handleEntry.UniqueProcessId, handleEntry.HandleValue, handleEntry.ObjectTypeIndex, out var fileHandle))
                    {
                        yield return fileHandle;
                    }

                    offset += size;
                }
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                    Marshal.FreeHGlobal(ptr);
            }
        }

19 View Source File : UnmanagedBuffer.cs
License : Apache License 2.0
Project Creator : aequabit

public bool Read<TResult>(out TResult data) where TResult: struct
        {
            data = default(TResult);
            try
            {
                if (this.Size < Marshal.SizeOf(typeof(TResult)))
                {
                    throw new InvalidCastException("Not enough unmanaged memory is allocated to contain this structure type.");
                }
                data = (TResult) Marshal.PtrToStructure(this.Pointer, typeof(TResult));
                return true;
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : utils.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast

public static T GetStructBE<T>(byte[] data, int offset)
        {
            int size = Marshal.SizeOf(typeof(T));
            Byte[] data_trimed = SubArray(data, offset, size);
            Array.Reverse(data_trimed);
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(data_trimed, 0, structPtr, size);
            T r = (T)Marshal.PtrToStructure(structPtr, typeof(T));
            Marshal.FreeHGlobal(structPtr);
            return r;
        }

19 View Source File : ChangeKey.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            if (nCode >= 0)
            {
                theKey = (KeyHook)Marshal.PtrToStructure(lp, typeof(KeyHook));
                // Keyboard Hook Time /////////////////////////////////////////////////////////////////////////////////////////

                if (theKey.flags < 128 && (int)theKey.Key != (int)Keys.Return)
                {
                    _pressedKey = theKey.Key;

                    _pressedKeyName = MainForm.VirtualKeyName(_pressedKey);

                    lblKeyName.Text = _pressedKeyName; //+ " " + _pressedKey.ToString(); //+ " " + nonVirtualKey; //MainForm.KeyName(theKey.Key)
                    btnAccept.Enabled = true;
                    this.ActiveControl = btnAccept;
                }

                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            return CallNextHookEx(ptrHook, nCode, wp, lp);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            //using (StreamWriter sw = File.AppendText("keys.log"))
            //{
                //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  nCode=" + nCode);

                if (nCode >= 0) //(proc != null && nCode >= 0)
                {
                    theKey = (KeyHook)Marshal.PtrToStructure(lp, typeof(KeyHook));
                    // Keyboard Hook Time /////////////////////////////////////////////////////////////////////////////////////////

                    //if (theKey.flags < 128) MessageBox.Show(theKey.key.ToString() + "\n" + ((int)theKey.key).ToString());

                    //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  key=" + (int)theKey.Key + " code=" + theKey.Code + " flags=" + theKey.flags + " extra=" + theKey.extra);

                    if (hotKeys && ((IList<Keys>)catchKeys).Contains(theKey.Key))
                    {
                        if (theKey.flags < 128 && currentKey != theKey.Key)
                        {
                            TimerReset();
                            currentKey = theKey.Key;
                            UpdateMem();
                            TimerHoldKey.Start();
                        }
                        else if (theKey.flags >= 128)
                        {
                            TimerReset();
                            currentKey = Keys.None;
                            SaveSettings();
                        }
                    }

                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                return CallNextHookEx(ptrHook, nCode, wp, lp);

            //}
        }

19 View Source File : MouseHook.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
            {
                MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                MouseAction(null, new EventArgs());
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            if (proc != null && nCode >= 0)
            {
                theKey = (KeyHook)Marshal.PtrToStructure(lp, typeof(KeyHook));
                // Keyboard Hook Time /////////////////////////////////////////////////////////////////////////////////////////

                //if (theKey.flags < 128) MessageBox.Show(theKey.key.ToString() + "\n" + ((int)theKey.key).ToString());

                if (((IList<Keys>)catchKeys).Contains(theKey.Key) && hotKeys)
                {
                    if (theKey.flags < 128 && currentKey != theKey.Key)
                    {
                        TimerReset();
                        currentKey = theKey.Key;
                        UpdateMem();
                        TimerHoldKey.Start();
                    }
                    else if (theKey.flags >= 128)
                    {
                        TimerReset();
                        currentKey = Keys.None;
                        SaveData();
                    }
                }

                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            return CallNextHookEx(ptrHook, nCode, wp, lp);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            //using (StreamWriter sw = File.AppendText("keys.log"))
            //{
                //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  nCode=" + nCode);

                if (nCode >= 0) //(proc != null && nCode >= 0)
                {
                    theKey = (KeyHook)Marshal.PtrToStructure(lp, typeof(KeyHook));
                    // Keyboard Hook Time /////////////////////////////////////////////////////////////////////////////////////////

                    //if (theKey.flags < 128) MessageBox.Show(theKey.key.ToString() + "\n" + ((int)theKey.key).ToString());

                    //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  key=" + (int)theKey.Key + " code=" + theKey.Code + " flags=" + theKey.flags + " extra=" + theKey.extra);

                    if (((IList<Keys>)catchKeys).Contains(theKey.Key) && hotKeys)
                    {
                        if (theKey.flags < 128 && currentKey != theKey.Key)
                        {
                            TimerReset();
                            currentKey = theKey.Key;
                            UpdateMem();
                            TimerHoldKey.Start();
                        }
                        else if (theKey.flags >= 128)
                        {
                            TimerReset();
                            currentKey = Keys.None;
                            SaveSettings();
                        }
                    }

                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                return CallNextHookEx(ptrHook, nCode, wp, lp);

            //}
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

static object ResolveToType(byte[] bytes, Type type)
        {
            object val;

            if (type == typeof(int))
            {
                val = BitConverter.ToInt32(bytes, 0);
            }
            else if (type == typeof(uint))
            {
                val = BitConverter.ToUInt32(bytes, 0);
            }
            else if (type == typeof(float))
            {
                val = BitConverter.ToSingle(bytes, 0);
            }
            else if (type == typeof(double))
            {
                val = BitConverter.ToDouble(bytes, 0);
            }
            else if (type == typeof(byte))
            {
                val = bytes[0];
            }
            else if (type == typeof(bool))
            {
                if (bytes == null)
                    val = false;
                else
                    val = (bytes[0] != 0);
            }
            else if (type == typeof(short))
            {
                val = BitConverter.ToInt16(bytes, 0);
            }
            else // probably a struct
            {
                var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                try
                {
                    val = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), type);
                }
                finally
                {
                    handle.Free();
                }
            }

            return val;
        }

19 View Source File : RawInputWnd.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void GetRawInputData(IntPtr hRawInput)
		{
			try
			{
				int bsCount = -1;
				int blen = 0;
				int hlen = Marshal.SizeOf(typeof(RAWINPUTHEADER));

				//TraceLogger.Instance.WriteLineInfo("Get RawInput data.");
				bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, IntPtr.Zero, ref blen, hlen);
				if ((bsCount == -1) || (blen < 1))
				{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer size."); }
				else
				{
					IntPtr pBuffer = Marshal.AllocHGlobal(blen);
					try
					{
						bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, pBuffer, ref blen, hlen);
						if (bsCount != blen)
						{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer data."); }
						else
						{
							RawInput ri = (RawInput)Marshal.PtrToStructure(pBuffer, typeof(RawInput));
							FireRawInputEvent(ref ri);
						}
					}
					catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
					finally
					{
						Marshal.FreeHGlobal(pBuffer);
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
		}

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static RemoteSessionInfo GetRemoteSessionInfo()
		{
			RemoteSessionInfo rsi = new RemoteSessionInfo();
			try
			{
				int sessionId = Process.GetCurrentProcess().SessionId;
				StringBuilder sb;
				IntPtr ptr;
				int len;

				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSUserName, out sb, out len))
					rsi.UserName = sb.ToString();
				
				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSDomainName, out sb, out len))
					rsi.Domain = sb.ToString();
				
				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientName, out sb, out len))
					rsi.ClientName = sb.ToString();

				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientAddress, out ptr, out len))
				{
					WTS_CLIENT_ADDRESS addr = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(ptr, typeof(WTS_CLIENT_ADDRESS));
					if (addr.AddressFamily == util.AF_INET)
						rsi.ClientAddress = string.Format("{0}.{1}.{2}.{3}", new object[] { addr.Address[2], addr.Address[3], addr.Address[4], addr.Address[5] });
				}
		
				//if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientDisplay, out ptr, out len))
				//{
				//    WTS_CLIENT_DISPLAY disp = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(ptr, typeof(WTS_CLIENT_DISPLAY));
				//    rsi.ClientHResolution = disp.HorizontalResolution;
				//    rsi.ClientVResolution = disp.VerticalResolution;
				//    rsi.ClientColorDepth = disp.ColorDepth;
				//}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return rsi;
		}

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static int[] GetActiveSessions()
		{
			List<int> sessions = new List<int>();
			try
			{
				IntPtr pSessions = IntPtr.Zero;
				int count = 0;
				if (wtsapi32.WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessions, ref count))
				{
					IntPtr pSession = pSessions;
					for (int i = 0; i < count; ++i)
					{
						WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(pSession, typeof(WTS_SESSION_INFO));
						pSession = new IntPtr(pSession.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
						if (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive)
							sessions.Add(si.SessionId);
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return sessions.ToArray();
		}

19 View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public string[] GetUserGroups(string username)
		{
			List<string> groups = new List<string>();
			try
			{
				int entriesread;
				int totalentries;
				IntPtr pBuf;
				netapi32.NetUserGetLocalGroups(null, username, 0, 1,out pBuf, -1, out entriesread, out totalentries);
				if (entriesread > 0)
				{
					IntPtr pItem = pBuf;
					for (int i = 0; i < entriesread; ++i)
					{
						var groupinfo = (LOCALGROUP_USERS_INFO_0)Marshal.PtrToStructure(pItem, typeof(LOCALGROUP_USERS_INFO_0));
						pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_USERS_INFO_0)));
						groups.Add(groupinfo.lgrui0_name);
					}
				}
				netapi32.NetApiBufferFree(pBuf);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return groups.ToArray();
		}

19 View Source File : ObjRefHelper.cs
License : Apache License 2.0
Project Creator : airbus-cert

private static T IndexedGet<T>(IntPtr array_start, int index) {
            var array_offset = OffsetFor<T>(index);
            var struct_at_index = (T)Marshal.PtrToStructure(array_start + array_offset, typeof(T));
            return struct_at_index;
        }

19 View Source File : ObjRefHelper.cs
License : Apache License 2.0
Project Creator : airbus-cert

private static bool MarshalAndValidate<T>(IntPtr struct_ptr, Func<T, bool> validityChecker, out T destination_ptr) where T : struct
        {
            destination_ptr = default(T);
            if (IsNull(struct_ptr))
            {
                return false;
            }

            destination_ptr = (T)Marshal.PtrToStructure(struct_ptr, typeof(T));
            return validityChecker(destination_ptr);
        }

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

private static int GetParentProcess(IntPtr Handle)
        {
            var basicProcessInformation = new PROCESS_BASIC_INFORMATION();
            IntPtr pProcInfo = Marshal.AllocHGlobal(Marshal.SizeOf(basicProcessInformation));
            Marshal.StructureToPtr(basicProcessInformation, pProcInfo, true);
            NtQueryInformationProcess(Handle, PROCESSINFOCLreplaced.ProcessBasicInformation, pProcInfo, Marshal.SizeOf(basicProcessInformation), out int returnLength);
            basicProcessInformation = (PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(pProcInfo, typeof(PROCESS_BASIC_INFORMATION));

            return basicProcessInformation.InheritedFromUniqueProcessId;
        }

19 View Source File : ObjRefHelper.cs
License : Apache License 2.0
Project Creator : airbus-cert

private static YR_MATCH GetMatchFromObjRef(IntPtr objRef)
        {
            try
            {
                YR_MATCH yrMatch = (YR_MATCH)Marshal.PtrToStructure(objRef, typeof(YR_MATCH));
                return yrMatch;
            }
            catch
            {
                Debug.WriteLine($"Error for Match : {objRef}");
                return default;
            }
        }

19 View Source File : SteamVR_RenderModel.cs
License : MIT License
Project Creator : ajayyy

RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
	{
        var pRenderModel = System.IntPtr.Zero;

		EVRRenderModelError error;
		while ( true )
		{
			error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
			if (error != EVRRenderModelError.Loading)
				break;

			Sleep();
		}

		if (error != EVRRenderModelError.None)
		{
			Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
			return null;
		}

        var renderModel = MarshalRenderModel(pRenderModel);

		var vertices = new Vector3[renderModel.unVertexCount];
		var normals = new Vector3[renderModel.unVertexCount];
		var uv = new Vector2[renderModel.unVertexCount];

		var type = typeof(RenderModel_Vertex_t);
		for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
		{
			var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
			var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

			vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
			normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
			uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
		}

		int indexCount = (int)renderModel.unTriangleCount * 3;
		var indices = new short[indexCount];
		Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

		var triangles = new int[indexCount];
		for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
		{
			triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
			triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
			triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
		}

		var mesh = new Mesh();
		mesh.vertices = vertices;
		mesh.normals = normals;
		mesh.uv = uv;
		mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
		mesh.Optimize();
#endif
		//mesh.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

		// Check cache before loading texture.
		var material = materials[renderModel.diffuseTextureId] as Material;
		if (material == null || material.mainTexture == null)
		{
			var pDiffuseTexture = System.IntPtr.Zero;

			while (true)
			{
				error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
				if (error != EVRRenderModelError.Loading)
					break;

				Sleep();
			}

			if (error == EVRRenderModelError.None)
			{
				var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
				var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
				if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
				{
					texture.Apply();

					while (true)
					{
						error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
						if (error != EVRRenderModelError.Loading)
							break;

						Sleep();
					}
				}
				else
				{
					var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
					Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

					var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
					int iColor = 0;
					for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
					{
						for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
						{
							var r = textureMapData[iColor++];
							var g = textureMapData[iColor++];
							var b = textureMapData[iColor++];
							var a = textureMapData[iColor++];
							colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
						}
					}

					texture.SetPixels32(colors);
					texture.Apply();
				}

				material = new Material(shader != null ? shader : Shader.Find("Standard"));
				material.mainTexture = texture;
				//material.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

				materials[renderModel.diffuseTextureId] = material;

				renderModels.FreeTexture(pDiffuseTexture);
			}
			else
			{
				Debug.Log("Failed to load render model texture for render model " + renderModelName);
			}
		}

		// Delay freeing when we can since we'll often get multiple requests for the same model right
		// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
		if (!Application.isPlaying)
			renderModels.FreeRenderModel(pRenderModel);
		else
#endif
			StartCoroutine(FreeRenderModel(pRenderModel));

		return new RenderModel(mesh, material);
	}

19 View Source File : SteamVR_RenderModel.cs
License : MIT License
Project Creator : ajayyy

private RenderModel_t MarshalRenderModel(System.IntPtr pRenderModel)
    {
        if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
            (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
        {
            var packedModel = (RenderModel_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t_Packed));
            RenderModel_t model = new RenderModel_t();
            packedModel.Unpack(ref model);
            return model;
        }
        else
        {
            return (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
        }
    }

19 View Source File : SteamVR_RenderModel.cs
License : MIT License
Project Creator : ajayyy

private RenderModel_TextureMap_t MarshalRenderModel_TextureMap(System.IntPtr pRenderModel)
    {
        if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
            (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
        {
            var packedModel = (RenderModel_TextureMap_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t_Packed));
            RenderModel_TextureMap_t model = new RenderModel_TextureMap_t();
            packedModel.Unpack(ref model);
            return model;
        }
        else
        {
            return (RenderModel_TextureMap_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t));
        }
    }

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

public static void Setup(SigScanner scanner)
    {
        var props = typeof(Offsets).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
            .Select(i => (prop: i, Attribute: i.GetCustomAttribute<SigAttribute>())).Where(i => i.Attribute != null);

        List<Exception> exceptions = new List<Exception>(100);
        foreach ((PropertyInfo propertyInfo, SigAttribute sigAttribute) in props)
        {
            try
            {
                var sig = sigAttribute.SigString;
                sig = string.Join(' ', sig.Split(new[] { ' ' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
                    .Select(i => i == "?" ? "??" : i));

                IntPtr address;
                switch (sigAttribute)
                {
                    case StaticAddressAttribute:
                        address = scanner.GetStaticAddressFromSig(sig);
                        break;
                    case FunctionAttribute:
                        address = scanner.ScanText(sig);
                        break;
                    case OffsetAttribute:
                    {
                        address = scanner.ScanText(sig);
                        address += sigAttribute.Offset;
                        var structure = Marshal.PtrToStructure(address, propertyInfo.PropertyType);
                        propertyInfo.SetValue(null, structure);
                        PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {propertyInfo.PropertyType.FullName} {structure}");
                        continue;
                    }
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                address += sigAttribute.Offset;
                propertyInfo.SetValue(null, address);
                PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {address.ToInt64():X}");
            }
            catch (Exception e)
            {
                PluginLog.Error(e, $"[{nameof(OffsetManager)}][{propertyInfo?.Name}] failed to find sig : {sigAttribute?.SigString}");
                exceptions.Add(e);
            }
        }

        if (exceptions.Any())
        {
            throw new AggregateException(exceptions);
        }
    }

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

public static T BytesToStuct<T>(byte[] bytes) where T : struct
        {
            Type type = typeof(T);
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                throw new ArgumentException("bytes 的长度不足", nameof(bytes));
                //返回空
                //return default(T);
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return (T)obj;
        }

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

public static T BytesToStuct<T>(byte[] bytes, Int32 offset) where T : struct
        {
            Type type = typeof(T);
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length - offset)
            {
                throw new ArgumentException("bytes 的长度不足", nameof(bytes));
                //返回空
                //return default(T);
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, offset, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return (T)obj;
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : AlexanderPro

protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case NativeConstants.WM_COPYDATA:
                    {
                        var cds = (CopyDataStruct)Marshal.PtrToStructure(m.LParam, typeof(CopyDataStruct));
                        var preplacedword = Marshal.PtrToStringAuto(cds.lpData);
                        txtContent.Text = preplacedword;
                        txtContent.ScrollTextToEnd();
                        OnContentChanged();
                    }
                    break;
            }

            base.WndProc(ref m);
        }

19 View Source File : MouseLLHook.cs
License : MIT License
Project Creator : AlexanderPro

public override void ProcessWindowMessage(ref Message m)
        {
            if (m.Msg == _msgIdMouseLL)
            {
                RaiseEvent(MouseLLEvent, new BasicHookEventArgs(m.WParam, m.LParam));

                var msl = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(m.LParam, typeof(MSLLHOOKSTRUCT));
                if (m.WParam.ToInt64() == WM_MOUSEMOVE)
                {
                    RaiseEvent(MouseMove, new MouseEventArgs(MouseButtons.None, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_LBUTTONDOWN)
                {
                    RaiseEvent(MouseDown, new MouseEventArgs(MouseButtons.Left, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_RBUTTONDOWN)
                {
                    RaiseEvent(MouseDown, new MouseEventArgs(MouseButtons.Right, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_LBUTTONUP)
                {
                    RaiseEvent(MouseUp, new MouseEventArgs(MouseButtons.Left, 0, msl.pt.X, msl.pt.Y, 0));
                }
                else if (m.WParam.ToInt64() == WM_RBUTTONUP)
                {
                    RaiseEvent(MouseUp, new MouseEventArgs(MouseButtons.Right, 0, msl.pt.X, msl.pt.Y, 0));
                }
            }
            else if (m.Msg == _msgIdMouseLLHookReplaced)
            {
                RaiseEvent(HookReplaced, EventArgs.Empty);
            }
        }

19 View Source File : MouseHook.cs
License : MIT License
Project Creator : AlexanderPro

private int HookProc(int code, int wParam, IntPtr lParam)
        {
            if (code == HC_ACTION)
            {
                if (_mouseButton != MouseButton.None && 
                    (wParam == WM_LBUTTONDOWN || wParam == WM_RBUTTONDOWN || wParam == WM_MBUTTONDOWN || wParam == WM_LBUTTONUP || wParam == WM_RBUTTONUP || wParam == WM_MBUTTONUP))
                {
                    var key1 = true;
                    var key2 = true;

                    if (_key1 != VirtualKeyModifier.None)
                    {
                        var key1State = GetAsyncKeyState((int)_key1) & 0x8000;
                        key1 = Convert.ToBoolean(key1State);
                    }

                    if (_key2 != VirtualKeyModifier.None)
                    {
                        var key2State = GetAsyncKeyState((int)_key2) & 0x8000;
                        key2 = Convert.ToBoolean(key2State);
                    }

                    if (key1 && key2 && ((_mouseButton == MouseButton.Left && wParam == WM_LBUTTONDOWN) || (_mouseButton == MouseButton.Right && wParam == WM_RBUTTONDOWN) || (_mouseButton == MouseButton.Middle && wParam == WM_MBUTTONDOWN)))
                    {
                        var handler = Hooked;
                        if (handler != null)
                        {
                            var mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
                            var eventArgs = new MouseEventArgs(mouseHookStruct.pt);
                            handler.BeginInvoke(this, eventArgs, null, null);
                            return 1;
                        }
                    }

                    if (key1 && key2 && ((_mouseButton == MouseButton.Left && wParam == WM_LBUTTONUP) || (_mouseButton == MouseButton.Right && wParam == WM_RBUTTONUP) || (_mouseButton == MouseButton.Middle && wParam == WM_MBUTTONUP)))
                    {
                        return 1;
                    }
                }
            }

            return CallNextHookEx(_hookHandle, code, wParam, lParam);
        }

19 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

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

19 View Source File : ADL.cs
License : MIT License
Project Creator : AlexGyver

public static int ADL_Adapter_AdapterInfo_Get(ADLAdapterInfo[] info) {
      int elementSize = Marshal.SizeOf(typeof(ADLAdapterInfo));
      int size = info.Length * elementSize;
      IntPtr ptr = Marshal.AllocHGlobal(size);
      int result = _ADL_Adapter_AdapterInfo_Get(ptr, size);
      for (int i = 0; i < info.Length; i++)
        info[i] = (ADLAdapterInfo)
          Marshal.PtrToStructure((IntPtr)((long)ptr + i * elementSize),
          typeof(ADLAdapterInfo));
      Marshal.FreeHGlobal(ptr);

      // the ADLAdapterInfo.VendorID field reported by ADL is wrong on 
      // Windows systems (parse error), so we fix this here
      for (int i = 0; i < info.Length; i++) {
        // try Windows UDID format
        Match m = Regex.Match(info[i].UDID, "PCI_VEN_([A-Fa-f0-9]{1,4})&.*");
        if (m.Success && m.Groups.Count == 2) {
          info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 16);
          continue;
        }
        // if above failed, try Unix UDID format
        m = Regex.Match(info[i].UDID, "[0-9]+:[0-9]+:([0-9]+):[0-9]+:[0-9]+");
        if (m.Success && m.Groups.Count == 2) {
          info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 10);
        }
      }

      return result;
    }

19 View Source File : GadgetWindow.cs
License : MIT License
Project Creator : AlexGyver

protected override void WndProc(ref Message message) {
      switch (message.Msg) {
        case WM_COMMAND: {
            // need to dispatch the message for the context menu
            if (message.LParam == IntPtr.Zero)
              commandDispatch.Invoke(null, new object[] { 
              message.WParam.ToInt32() & 0xFFFF });
          } break;
        case WM_NCHITTEST: {
            message.Result = (IntPtr)HitResult.Caption;
            if (HitTest != null) {
              Point p = new Point(
                Macros.GET_X_LPARAM(message.LParam) - location.X,
                Macros.GET_Y_LPARAM(message.LParam) - location.Y
              );
              HitTestEventArgs e = new HitTestEventArgs(p, HitResult.Caption);
              HitTest(this, e);
              message.Result = (IntPtr)e.HitResult;
            }
          } break;
        case WM_NCLBUTTONDBLCLK: {
            if (MouseDoubleClick != null) {
              MouseDoubleClick(this, new MouseEventArgs(MouseButtons.Left, 2,
                Macros.GET_X_LPARAM(message.LParam) - location.X,
                Macros.GET_Y_LPARAM(message.LParam) - location.Y, 0));
            }
            message.Result = IntPtr.Zero;
          } break;
        case WM_NCRBUTTONDOWN: {
            message.Result = IntPtr.Zero;
          } break;
        case WM_NCRBUTTONUP: {
            if (contextMenu != null)
              ShowContextMenu(new Point(
                Macros.GET_X_LPARAM(message.LParam),
                Macros.GET_Y_LPARAM(message.LParam)
              ));
            message.Result = IntPtr.Zero;
          } break;
        case WM_WINDOWPOSCHANGING: {
            WindowPos wp = (WindowPos)Marshal.PtrToStructure(
              message.LParam, typeof(WindowPos));
            
            if (!lockPositionAndSize) {
              // prevent the window from leaving the screen
              if ((wp.flags & SWP_NOMOVE) == 0) {
                Rectangle rect = Screen.GetWorkingArea(
                  new Rectangle(wp.x, wp.y, wp.cx, wp.cy));
                const int margin = 16;
                wp.x = Math.Max(wp.x, rect.Left - wp.cx + margin);
                wp.x = Math.Min(wp.x, rect.Right - margin);
                wp.y = Math.Max(wp.y, rect.Top - wp.cy + margin);
                wp.y = Math.Min(wp.y, rect.Bottom - margin);
              }

              // update location and fire event
              if ((wp.flags & SWP_NOMOVE) == 0) {
                if (location.X != wp.x || location.Y != wp.y) {
                  location = new Point(wp.x, wp.y);
                  if (LocationChanged != null)
                    LocationChanged(this, EventArgs.Empty);
                }
              }

              // update size and fire event
              if ((wp.flags & SWP_NOSIZE) == 0) {
                if (size.Width != wp.cx || size.Height != wp.cy) {
                  size = new Size(wp.cx, wp.cy);
                  if (SizeChanged != null)
                    SizeChanged(this, EventArgs.Empty);
                }
              } 

              // update the size of the layered window
              if ((wp.flags & SWP_NOSIZE) == 0) {
                NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero,
                  IntPtr.Zero, ref size, IntPtr.Zero, IntPtr.Zero, 0,
                  IntPtr.Zero, 0);                
              }

              // update the position of the layered window
              if ((wp.flags & SWP_NOMOVE) == 0) {
                NativeMethods.SetWindowPos(Handle, IntPtr.Zero, 
                  location.X, location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | 
                  SWP_NOZORDER | SWP_NOSENDCHANGING);
              }
            }
            
            // do not forward any move or size messages
            wp.flags |= SWP_NOSIZE | SWP_NOMOVE;

            // suppress any frame changed events
            wp.flags &= ~SWP_FRAMECHANGED;

            Marshal.StructureToPtr(wp, message.LParam, false);                      
            message.Result = IntPtr.Zero;
          } break;
        default: {
            base.WndProc(ref message);
          } break;
      }      
    }

19 View Source File : graybitmap.cs
License : MIT License
Project Creator : altimesh

public static GrayBitmap Load(string filename)
        {
            using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open)))
            {
                byte[] header = br.ReadBytes(54);
                GCHandle gch = GCHandle.Alloc(header, GCHandleType.Pinned);

                // read headers
                FileHeader fh = (FileHeader)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(header, 0), typeof(FileHeader));
                BitmapInfoHeader bih = (BitmapInfoHeader)Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(header, 14), typeof(BitmapInfoHeader));

                // read the palette
                br.ReadBytes((int)(bih.numberOfColorsInPalette * 4));

                //Console.Out.WriteLine("Loading bitmap file width = {0} - height = {1}", bih.width, bih.height) ;
                
                GrayBitmap res = new GrayBitmap(bih.width, bih.height);

                // read data - note that bmp starts with bottom-left corner
                for (int y = 0; y < res.height; ++y)
                    br.Read(res.data, (int)res.width *((int)res.height - 1 - y), (int)res.width);
                return res;
            }
        }

19 View Source File : NetworkClass.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private static ParseResult Parse(byte[] data)
        {
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
            FFXIVMessageHeader head = (FFXIVMessageHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FFXIVMessageHeader));
            handle.Free();

            ParseResult result = new ParseResult();
            result.header = head;
            result.data = data;

            return result;
        }

19 View Source File : nfapinet.cs
License : MIT License
Project Creator : AmazingDM

public static void udpReceive(ulong id, IntPtr remoteAddress, IntPtr buf, int len, IntPtr options)
        {
            if (options.ToInt64() != 0)
            {
                NF_UDP_OPTIONS optionsCopy = (NF_UDP_OPTIONS)Marshal.PtrToStructure((IntPtr)options, typeof(NF_UDP_OPTIONS));
                int optionsLen = 8 + optionsCopy.optionsLength;
                m_pEventHandler.udpReceive(id, remoteAddress, buf, len, options, optionsLen);
            }
            else
            {
                m_pEventHandler.udpReceive(id, remoteAddress, buf, len, (IntPtr)null, 0);
            }
        }

19 View Source File : nfapinet.cs
License : MIT License
Project Creator : AmazingDM

public static void udpSend(ulong id, IntPtr remoteAddress, IntPtr buf, int len, IntPtr options)
        {
            if (options.ToInt64() != 0)
            {
                NF_UDP_OPTIONS optionsCopy = (NF_UDP_OPTIONS)Marshal.PtrToStructure((IntPtr)options, typeof(NF_UDP_OPTIONS));
                int optionsLen = 8 + optionsCopy.optionsLength;
                m_pEventHandler.udpSend(id, remoteAddress, buf, len, options, optionsLen);
            }
            else
            {
                m_pEventHandler.udpSend(id, remoteAddress, buf, len, (IntPtr)null, 0);
            }
        }

19 View Source File : CommandMapper.cs
License : Apache License 2.0
Project Creator : AmpScm

static string GetText(IntPtr pCmdTextInt)
        {
            Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));

            // Punt early if there is no text in the structure.
            //
            if (pCmdText.cwActual == 0)
            {
                return "";
            }

            char[] text = new char[pCmdText.cwActual - 1];

            Marshal.Copy((IntPtr)((long)pCmdTextInt + _offset_rgwz), text, 0, text.Length);

            StringBuilder s = new StringBuilder(text.Length);
            s.Append(text);
            return s.ToString();
        }

19 View Source File : SmartListView.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void WndProc(ref Message m)
        {
            if (!DesignMode)
            {
                switch (m.Msg)
                {
                    case NativeMethods.WM_CONTEXTMENU:
                        {
                            uint pos = unchecked((uint)m.LParam);

                            Select();

                            OnShowContextMenu(new MouseEventArgs(Control.MouseButtons, 1,
                                unchecked((short)(ushort)(pos & 0xFFFF)),
                                unchecked((short)(ushort)(pos >> 16)), 0));

                            return;
                        }

                    case NativeMethods.OCM_NOTIFY:
                        // Receives ListView notifications
                        if (CheckBoxes && StrictCheckboxesClick)
                        {
                            NMHDR hdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));

                            if (hdr.code == NativeMethods.NM_DBLCLK)
                            {
                                Point mp = PointToClient(MousePosition);
                                ListViewHitTestInfo hi = HitTest(mp);

                                if (hi != null && hi.Location != ListViewHitTestLocations.StateImage)
                                {
                                    MouseEventArgs me = new MouseEventArgs(MouseButtons.Left, 2, mp.X, mp.Y, 0);
                                    OnDoubleClick(me);
                                    OnMouseDoubleClick(me);
                                    return;
                                }
                            }
                        }
                        break;
                    case NativeMethods.WM_NOTIFY:
                        // Receives child control notifications (like that of the header control)
                        if (CheckBoxes && ShowSelectAllCheckBox)
                        {
                            NMHDR hdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));

                            if (hdr.code == NativeMethods.HDN_ITEMSTATEICONCLICK)
                            {
                                CancelEventArgs ce = new CancelEventArgs();

                                PerformSelectAllCheckedChange(ce);

                                if (ce.Cancel)
                                    return;
                            }
                        }
                        break;

                    case NativeMethods.WM_HSCROLL:
                        WmHScroll(ref m);
                        break;
                    case NativeMethods.WM_VSCROLL:
                        WmVScroll(ref m);
                        break;
                }
            }
            base.WndProc(ref m);
        }

See More Examples