System.Runtime.InteropServices.Marshal.SizeOf(System.Type)

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

1849 Examples 7

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 : ProxySetting.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool SetProxy(string strProxy, string exceptions, int type)
        {
            InternetPerConnOptionList list = new InternetPerConnOptionList();

            int optionCount = 1;
            if (type == 1)
            {
                optionCount = 1;
            }
            else if (type == 2 || type == 4)
            {
                optionCount = Utils.IsNullOrEmpty(exceptions) ? 2 : 3;
            }

            int m_Int = (int)PerConnFlags.PROXY_TYPE_DIRECT;
            PerConnOption m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
            if (type == 2)
            {
                m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY);
                m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
            }
            else if (type == 4)
            {
                m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_AUTO_PROXY_URL);
                m_Option = PerConnOption.INTERNET_PER_CONN_AUTOCONFIG_URL;
            }

            //int optionCount = Utils.IsNullOrEmpty(strProxy) ? 1 : (Utils.IsNullOrEmpty(exceptions) ? 2 : 3);
            InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
            // USE a proxy server ...
            options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
            //options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
            options[0].m_Value.m_Int = m_Int;
            // use THIS proxy server
            if (optionCount > 1)
            {
                options[1].m_Option = m_Option;
                options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
                // except for these addresses ...
                if (optionCount > 2)
                {
                    options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPreplaced;
                    options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
                }
            }

            // default stuff
            list.dwSize = Marshal.SizeOf(list);
            list.szConnection = IntPtr.Zero;
            list.dwOptionCount = options.Length;
            list.dwOptionError = 0;


            int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
            // make a pointer out of all that ...
            IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
            // copy the array over into that spot in memory ...
            for (int i = 0; i < options.Length; ++i)
            {
                if (Environment.Is64BitOperatingSystem)
                {
                    IntPtr opt = new IntPtr(optionsPtr.ToInt64() + (i * optSize));
                    Marshal.StructureToPtr(options[i], opt, false);
                }
                else
                {
                    IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
                    Marshal.StructureToPtr(options[i], opt, false);
                }
            }

            list.options = optionsPtr;

            // and then make a pointer out of the whole list
            IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize);
            Marshal.StructureToPtr(list, ipcoListPtr, false);

            // and finally, call the API method!
            int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
               InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
               ipcoListPtr, list.dwSize) ? -1 : 0;
            if (returnvalue == 0)
            {  // get the error codes, they might be helpful
                returnvalue = Marshal.GetLastWin32Error();
            }
            // FREE the data ASAP
            Marshal.FreeCoTaskMem(optionsPtr);
            Marshal.FreeCoTaskMem(ipcoListPtr);
            if (returnvalue > 0)
            {  // throw the error codes, they might be helpful
                //throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return (returnvalue < 0);
        }

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 : SkyscraperManager.cs
License : MIT License
Project Creator : a3geek

private ComputeBuffer CreateBuffer<T>(int count)
        {
            return new ComputeBuffer(count, Marshal.SizeOf(typeof(T)), ComputeBufferType.Default);
        }

19 View Source File : CarsManager.cs
License : MIT License
Project Creator : a3geek

public void Initialize(SkyscraperManager skyscraper)
        {
            this.skyscraper = skyscraper;

            var roads = skyscraper.CityArea.Roads;
            var ids = roads.Keys;

            this.cars = new Car[this.num];
            this.simpleCars = new SimpleCar[this.num];

            for(var i = 0; i < this.num; i++)
            {
                var id = ids.ElementAt(Random.Range(0, ids.Count));

                this.cars[i] = new Car(roads[id], this.offset);
                this.cars[i].Update(this.skyscraper.CityArea, this.speed, this.straightRate);

                this.simpleCars[i] = this.cars[i];
            }

            this.geomBuffer = new ComputeBuffer(this.cars.Length, Marshal.SizeOf(typeof(SimpleCar)), ComputeBufferType.Default);
            this.geomBuffer.SetData(this.simpleCars.ToArray());
        }

19 View Source File : DecorationManager.cs
License : MIT License
Project Creator : a3geek

public void Initialize(SkyscraperManager skyscraper)
        {
            var decos = skyscraper.Builder.Decos;

            this.buffer?.Release();
            this.timesBuffer?.Release();

            if(decos.Count <= 0)
            {
                this.timers = new float[0];

                return;
            }

            this.buffer = new ComputeBuffer(decos.Count, Marshal.SizeOf(typeof(DecorationData)), ComputeBufferType.Default);
            this.buffer.SetData(decos.ToArray());

            this.timesBuffer = new ComputeBuffer(decos.Count, Marshal.SizeOf(typeof(Times)), ComputeBufferType.Default);
            this.timers = new float[this.buffer.count];
            this.times = new Times[this.buffer.count];

            for(var i = 0; i < this.times.Length; i++)
            {
                this.timers[i] = Random.value;
                this.times[i].time = this.curve.Evaluate(this.timers[i]);
            }

            this.timesBuffer.SetData(this.times);

            this.material.SetColor(PropNightColor, this.nightColor);
            this.material.SetColor(PropNoonColor, this.noonColor);
        }

19 View Source File : RoadsManager.cs
License : MIT License
Project Creator : a3geek

public void Initialize(SkyscraperManager skyscraper)
        {
            var roads = skyscraper.CityArea.Roads.Values.Select(r => (SimpleRoad)r);

            this.geomBuffer = new ComputeBuffer(roads.Count(), Marshal.SizeOf(typeof(SimpleRoad)), ComputeBufferType.Default);
            this.geomBuffer.SetData(roads.ToArray());

            var step = skyscraper.CityArea.MaxDistance / skyscraper.CityArea.Interval;
            this.vertsCount = Mathf.CeilToInt(step / MaxPointPerGeom);
        }

19 View Source File : MouseWatcher.cs
License : MIT License
Project Creator : a1xd

public void ReadMouseMove(Message message)
        {
            RawInput rawInput;
            int size = Marshal.SizeOf(typeof(RawInput));
            _ = GetRawInputData(message.LParam, RawInputCommand.Input, out rawInput, ref size, Marshal.SizeOf(typeof(RAWINPUTHEADER)));

            bool relative = !rawInput.Data.Mouse.Flags.HasFlag(RawMouseFlags.MoveAbsolute);

            bool deviceMatch = false;
            foreach (var (handle, normalized) in SettingsManager.ActiveNormTaggedHandles)
            {
                if (handle == rawInput.Header.Device)
                {
                    deviceMatch = true;

                    if (normalized != LastMoveNormalized)
                    {
                        LastMoveDisplayFormat = normalized ?
                                                Constants.MouseMoveNormalizedFormat :
                                                Constants.MouseMoveDefaultFormat;
                        LastMoveNormalized = normalized;
                    }

                    break;
                }
            }

            if (relative && deviceMatch && (rawInput.Data.Mouse.LastX != 0 || rawInput.Data.Mouse.LastY != 0))
            {
                var time = Stopwatch.Elapsed.TotalMilliseconds;
                Stopwatch.Restart();
                time = time > 100 ? 100 : time;
                time = time > (PollTime * 0.8) ? time : (PollTime * 0.8);

                double x = rawInput.Data.Mouse.LastX;
                double y = rawInput.Data.Mouse.LastY;

                // strip negative directional multipliers, charts calculated from positive input

                Vec2<double> dirMults = new Vec2<double>
                {
                    x = SettingsManager.ActiveProfile.lrSensRatio,
                    y = SettingsManager.ActiveProfile.udSensRatio
                };

                if (dirMults.x > 0 && x < 0)
                {
                    x /= dirMults.x;
                }

                if (dirMults.y > 0 && y < 0)
                {
                    y /= dirMults.y;
                }

                MouseData.Set(rawInput.Data.Mouse.LastX, rawInput.Data.Mouse.LastY);
                AccelCharts.MakeDots(x, y, time);
            }

        }

19 View Source File : UacHelper.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static bool IsProcessElevated()
        {
            if (IsUacEnabled())
            {
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
                {
                    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                }

                try
                {
                    TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;

                    int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
                    uint returnedSize = 0;

                    IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                    try
                    {
                        bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                        if (success)
                        {
                            elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
                            bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
                            return isProcessAdmin;
                        }
                        else
                        {
                            throw new ApplicationException("Unable to determine the current elevation.");
                        }
                    }
                    finally
                    {
                        if (elevationTypePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(elevationTypePtr);
                        }
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
            }
            else
            {
                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new(idenreplacedy);
                bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
                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 : OvrAvatar.cs
License : MIT License
Project Creator : absurd-joy

static public IntPtr GetRenderPart(ovrAvatarComponent component, UInt32 renderPartIndex)
    {
        return Marshal.ReadIntPtr(component.renderParts, Marshal.SizeOf(typeof(IntPtr)) * (int)renderPartIndex);
    }

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 : 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 : 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 : WindowInBandWrapper.cs
License : MIT License
Project Creator : ADeltaX

public void CreateWindowInBand()
        {
            WNDCLreplacedEX wind_clreplaced = new WNDCLreplacedEX();
            wind_clreplaced.cbSize = Marshal.SizeOf(typeof(WNDCLreplacedEX));
            wind_clreplaced.hbrBackground = (IntPtr)1 + 1;
            wind_clreplaced.cbClsExtra = 0;
            wind_clreplaced.cbWndExtra = 0;
            wind_clreplaced.hInstance = Process.GetCurrentProcess().Handle;
            wind_clreplaced.hIcon = IntPtr.Zero;
            wind_clreplaced.lpszMenuName = _window.replacedle;
            wind_clreplaced.lpszClreplacedName = "WIB_" + Guid.NewGuid();
            wind_clreplaced.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(delegWndProc);
            wind_clreplaced.hIconSm = IntPtr.Zero;
            ushort regResult = RegisterClreplacedEx(ref wind_clreplaced);

            if (regResult == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            _window.ShowActivated = true;

#if RELEASE_UIACCESS
            //Remember to change uiaccess to "true" in app.manifest

            IntPtr hWnd = CreateWindowInBand(
                    (int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
                    regResult,
                    _window.replacedle,
                    (uint)WindowStyles.WS_POPUP,
                    0,
                    0,
                    (int)0,
                    (int)0,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    wind_clreplaced.hInstance,
                    IntPtr.Zero,
                    (int)ZBID.ZBID_UIACCESS);

#else
            //Remember to change uiaccess to "false" in app.manifest

            IntPtr hWnd = CreateWindowInBand(
                    (int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
                    regResult,
                    _window.replacedle,
                    (uint)WindowStyles.WS_POPUP,
                    0,
                    0,
                    (int)0,
                    (int)0,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    wind_clreplaced.hInstance,
                    IntPtr.Zero,
                    (int)ZBID.ZBID_DEFAULT);

#endif

            if (hWnd == IntPtr.Zero)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            new AcrylicBlur(hWnd).EnableBlur();

            HwndSourceParameters param = new HwndSourceParameters
            {
                WindowStyle = 0x10000000 | 0x40000000,
                ParentWindow = hWnd,
                UsesPerPixelOpacity = true
            };

            HwndSource src = new HwndSource(param)
            {
                RootVisual = (Visual)_window.Content
            };
            src.CompositionTarget.BackgroundColor = Colors.Transparent;

            src.ContentRendered += Src_ContentRendered;

            UpdateWindow(hWnd);

            _inBandWindowHandle = hWnd;
        }

19 View Source File : MediaPlaybackDataSource.cs
License : MIT License
Project Creator : ADeltaX

public Stream GetThumbnailStream()
        {
            Stream outStream = null;

            IPropertyStore propStore;

            if (numSelectInterface == 20279)
                playbackDataSource_20279.GetMediaObjectInfo(out propStore);
            else
                playbackDataSource_10586.GetMediaObjectInfo(out propStore);

            if (propStore != null && propStore.GetValue(ref PKEY_ThumbnailStream, out PROPVARIANT pVariant) == 0 && pVariant.vt == VARTYPE.VT_STREAM)
            {
                var inStream = (IStream)Marshal.GetObjectForIUnknown(pVariant.union.pStream);
                outStream = new MemoryStream();

                int cb = 4096;
                byte[] buffer = new byte[cb];
                int read = 0;

                do
                {
                    IntPtr bytesRead = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
                    try
                    {
                        inStream.Read(buffer, cb, bytesRead);
                        read = Marshal.ReadInt32(bytesRead);
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(bytesRead);
                    }
                    outStream.Write(buffer, 0, read);
                } while (read > 0);

                outStream.Seek(0, SeekOrigin.Begin);

                NativeMethods.PropVariantClear(ref pVariant);
            }

            return outStream;
        }

19 View Source File : CreateValueWindow.xaml.cs
License : MIT License
Project Creator : ADeltaX

private void ValueTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var hndl = new WindowInteropHelper(this).EnsureHandle();
            IntPtr brush = CreateSolidBrush(uint.MinValue);
            SetClreplacedLong(hndl, -10, brush);

            SetWindowTheme(hndl, "DarkMode_Explorer", IntPtr.Zero);

            int attrValue = 1; //TRUE
            DwmSetWindowAttribute(hndl, 20, ref attrValue, Marshal.SizeOf(typeof(int)));

            //DARK THEME ^

            var val = (DataTypeEnum)ValueTypeComboBox.SelectedItem;

            if (valueDataSet != null)
            {
                valueDataSet.PropertyChanged -= ValueDataSet_PropertyChanged;
                valueDataSet = null;
                ContainerGrid.Children.Clear();

                //TODO: additional check when "if key !exists" is implemented
                OkButton.IsEnabled = true;
            }

            if (val == DataTypeEnum.RegUwpString)
            {
                var componentControl = new StringComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(250);
                ResizeMode = ResizeMode.CanResizeWithGrip;
            }
            else if (val == DataTypeEnum.RegUwpBoolean)
            {
                var componentControl = new BooleanComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if ((int)val >= (int)DataTypeEnum.RegUwpByte &&
                        (int)val <= (int)DataTypeEnum.RegUwpDouble) //byte, int16, uint16, int32, uint32, int64, uint64, double, single
            {
                var componentControl = new IntComponent(val);
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if (val == DataTypeEnum.RegUwpDateTimeOffset)
            {
                var componentControl = new DateTimeOffsetComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if (val == DataTypeEnum.RegUwpChar)
            {
                var componentControl = new CharComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if (val == DataTypeEnum.RegUwpGuid)
            {
                var componentControl = new GuidComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if (val == DataTypeEnum.RegUwpRect)
            {
                var componentControl = new RectComponent();
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }
            else if (val == DataTypeEnum.RegUwpPoint || val == DataTypeEnum.RegUwpSize)
            {
                var componentControl = new PointSizeComponent(val);
                ContainerGrid.Children.Add(componentControl);
                valueDataSet = componentControl;
                SetMinHeightAndHeight(210);
                ResizeMode = ResizeMode.NoResize;
            }

            valueDataSet.PropertyChanged += ValueDataSet_PropertyChanged;
        }

19 View Source File : TerrainMap.cs
License : MIT License
Project Creator : Adsito

public int BytesPerElement()
	{
		return Marshal.SizeOf(typeof(T));
	}

19 View Source File : NotifyIcon.cs
License : GNU General Public License v3.0
Project Creator : aduskin

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

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

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

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

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

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

19 View Source File : InteropValues.cs
License : GNU General Public License v3.0
Project Creator : aduskin

[SecuritySafeCritical]
         private static int SizeOf()
         {
            return Marshal.SizeOf(typeof(BITMAPINFO));
         }

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

private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1L))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (hModule.IsNull())
            {
                throw new ArgumentException("Invalid module handle.", "hModule");
            }
            byte[] buffer = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint) Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
            if (buffer != null)
            {
                ushort num = BitConverter.ToUInt16(buffer, 0);
                uint num2 = BitConverter.ToUInt32(buffer, 60);
                if (num == 0x5a4d)
                {
                    byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, hModule.Add((long) num2), (uint) Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
                    if ((buffer2 != null) && (BitConverter.ToUInt32(buffer2, 0) == 0x4550))
                    {
                        IMAGE_NT_HEADER32 result = new IMAGE_NT_HEADER32();
                        using (UnmanagedBuffer buffer3 = new UnmanagedBuffer(0x100))
                        {
                            if (buffer3.Translate<IMAGE_NT_HEADER32>(buffer2, out result))
                            {
                                return result.OptionalHeader.AddressOfEntryPoint;
                            }
                        }
                    }
                }
            }
            return 0;
        }

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

private static IntPtr MapModule(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, bool preserveHeaders = false)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1L))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (image == null)
            {
                throw new ArgumentException("Cannot map a non-existant PE Image.", "image");
            }
            int processId = WinAPI.GetProcessId(hProcess);
            if (processId == 0)
            {
                throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
            }
            IntPtr zero = IntPtr.Zero;
            IntPtr ptr = IntPtr.Zero;
            uint lpNumberOfBytesRead = 0;
            try
            {
                zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, image.NTHeader.OptionalHeader.SizeOfImage, 0x3000, 4);
                if (zero.IsNull())
                {
                    throw new InvalidOperationException("Unable to allocate memory in the remote process.");
                }
                PatchRelocations(image, zero);
                LoadDependencies(image, hProcess, processId);
                PatchImports(image, hProcess, processId);
                if (preserveHeaders)
                {
                    long num3 = (long) (((image.DOSHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_FILE_HEADER))) + ((long) 4L)) + image.NTHeader.FileHeader.SizeOfOptionalHeader);
                    byte[] buffer = new byte[num3];
                    if (image.Read(0L, SeekOrigin.Begin, buffer))
                    {
                        WinAPI.WriteProcessMemory(hProcess, zero, buffer, buffer.Length, out lpNumberOfBytesRead);
                    }
                }
                MapSections(image, hProcess, zero);
                if (image.NTHeader.OptionalHeader.AddressOfEntryPoint <= 0)
                {
                    return zero;
                }
                byte[] array = (byte[]) DLLMAIN_STUB.Clone();
                BitConverter.GetBytes(zero.ToInt32()).CopyTo(array, 11);
                ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
                if (ptr.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
                {
                    throw new InvalidOperationException("Unable to write stub to the remote process.");
                }
                IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, ptr, (uint) zero.Add(((long) image.NTHeader.OptionalHeader.AddressOfEntryPoint)).ToInt32(), 0, 0);
                if (WinAPI.WaitForSingleObject(hObject, 0x1388) != 0L)
                {
                    return zero;
                }
                WinAPI.GetExitCodeThread(hObject, out lpNumberOfBytesRead);
                if (lpNumberOfBytesRead == 0)
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                    throw new Exception("Entry method of module reported a failure " + Marshal.GetLastWin32Error().ToString());
                }
                WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
                WinAPI.CloseHandle(hObject);
            }
            catch (Exception exception)
            {
                if (!zero.IsNull())
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                }
                if (!ptr.IsNull())
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                }
                zero = IntPtr.Zero;
                throw exception;
            }
            return zero;
        }

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 : 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 : Apache License 2.0
Project Creator : aequabit

public static uint SizeOf(this Type t)
        {
            return (uint) Marshal.SizeOf(t);
        }

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

private static void PatchImports(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, int processId)
        {
            string lpBuffer = string.Empty;
            string str2 = string.Empty;
            foreach (IMAGE_IMPORT_DESCRIPTOR image_import_descriptor in image.EnumImports())
            {
                if (image.ReadString((long) image.GetPtrFromRVA(image_import_descriptor.Name), SeekOrigin.Begin, out lpBuffer, -1, null))
                {
                    IMAGE_THUNK_DATA image_thunk_data;
                    IntPtr zero = IntPtr.Zero;
                    zero = GetRemoteModuleHandle(lpBuffer, processId);
                    if (zero.IsNull())
                    {
                        throw new FileNotFoundException(string.Format("Unable to load dependent module '{0}'.", lpBuffer));
                    }
                    uint ptrFromRVA = image.GetPtrFromRVA(image_import_descriptor.FirstThunkPtr);
                    uint num2 = (uint) Marshal.SizeOf(typeof(IMAGE_THUNK_DATA));
                    while (image.Read<IMAGE_THUNK_DATA>((long) ptrFromRVA, SeekOrigin.Begin, out image_thunk_data) && (image_thunk_data.u1.AddressOfData > 0))
                    {
                        IntPtr hModule = IntPtr.Zero;
                        object lpProcName = null;
                        if ((image_thunk_data.u1.Ordinal & 0x80000000) == 0)
                        {
                            if (!image.ReadString((long) (image.GetPtrFromRVA(image_thunk_data.u1.AddressOfData) + 2), SeekOrigin.Begin, out str2, -1, null))
                            {
                                throw image.GetLastError();
                            }
                            lpProcName = str2;
                        }
                        else
                        {
                            lpProcName = (ushort) (image_thunk_data.u1.Ordinal & 0xffff);
                        }
                        if (!(hModule = WinAPI.GetModuleHandleA(lpBuffer)).IsNull())
                        {
                            IntPtr ptr = lpProcName.GetType().Equals(typeof(string)) ? WinAPI.GetProcAddress(hModule, (string) lpProcName) : WinAPI.GetProcAddress(hModule, (uint) (((ushort) lpProcName) & 0xffff));
                            if (!ptr.IsNull())
                            {
                                hModule = zero.Add((long) ptr.Subtract(((long) hModule.ToInt32())).ToInt32());
                            }
                        }
                        else
                        {
                            hModule = WinAPI.GetProcAddressEx(hProcess, zero, lpProcName);
                        }
                        if (hModule.IsNull())
                        {
                            throw new EntryPointNotFoundException(string.Format("Unable to locate imported function '{0}' from module '{1}' in the remote process.", str2, lpBuffer));
                        }
                        image.Write<int>((long) ptrFromRVA, SeekOrigin.Begin, hModule.ToInt32());
                        ptrFromRVA += num2;
                    }
                }
            }
        }

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

private static void PatchRelocations(JLibrary.PortableExecutable.PortableExecutable image, IntPtr pAlloc)
        {
            IMAGE_DATA_DIRECTORY image_data_directory = image.NTHeader.OptionalHeader.DataDirectory[5];
            if (image_data_directory.Size > 0)
            {
                IMAGE_BASE_RELOCATION image_base_relocation;
                uint num = 0;
                uint num2 = ((uint) pAlloc.ToInt32()) - image.NTHeader.OptionalHeader.ImageBase;
                uint ptrFromRVA = image.GetPtrFromRVA(image_data_directory.VirtualAddress);
                uint num4 = (uint) Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION));
                while ((num < image_data_directory.Size) && image.Read<IMAGE_BASE_RELOCATION>((long) ptrFromRVA, SeekOrigin.Begin, out image_base_relocation))
                {
                    int num5 = (int) ((image_base_relocation.SizeOfBlock - num4) / 2);
                    uint num6 = image.GetPtrFromRVA(image_base_relocation.VirtualAddress);
                    for (int i = 0; i < num5; i++)
                    {
                        ushort num7;
                        if (image.Read<ushort>((ptrFromRVA + num4) + (i << 1), SeekOrigin.Begin, out num7) && (((num7 >> 12) & 3) != 0))
                        {
                            uint num8;
                            uint num10 = num6 + ((uint) (num7 & 0xfff));
                            if (!image.Read<uint>((long) num10, SeekOrigin.Begin, out num8))
                            {
                                throw image.GetLastError();
                            }
                            image.Write<uint>(-4L, SeekOrigin.Current, num8 + num2);
                        }
                    }
                    num += image_base_relocation.SizeOfBlock;
                    ptrFromRVA += image_base_relocation.SizeOfBlock;
                }
            }
        }

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

public bool Read<TResult>(long offset, SeekOrigin origin, out TResult result) where TResult: struct
        {
            result = default(TResult);
            try
            {
                this._base.Seek(offset, origin);
                byte[] buffer = new byte[Marshal.SizeOf(typeof(TResult))];
                this._base.Read(buffer, 0, buffer.Length);
                if (!this._ubuffer.Translate<TResult>(buffer, out result))
                {
                    throw this._ubuffer.GetLastError();
                }
                return true;
            }
            catch (Exception exception)
            {
                return base.SetLastError(exception);
            }
        }

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

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

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

public bool Translate<TSource>(TSource data, out byte[] buffer) where TSource: struct
        {
            buffer = null;
            if (this.Commit<TSource>(data))
            {
                buffer = this.Read(Marshal.SizeOf(typeof(TSource)));
                this.SafeDecommit<TSource>();
            }
            return (buffer != null);
        }

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

public static bool ReadValue(Process process, IntPtr addr, Type type, out object val)
        {
            byte[] bytes;

            val = null;
            int size = type == typeof(bool) ? 1 : Marshal.SizeOf(type);
            if (!ReadBytes(process, addr, size, out bytes))
                return false;

            val = ResolveToType(bytes, type);

            return true;
        }

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

public static IEnumerable<MemoryBasicInformation> MemoryPages(this Process process, bool all = false)
        {
            // hardcoded values because GetSystemInfo / GetNativeSystemInfo can't return info for remote process
            var min = 0x10000L;
            var max = process.Is64Bit() ? 0x00007FFFFFFEFFFFL : 0x7FFEFFFFL;

            var mbiSize = (SizeT)Marshal.SizeOf(typeof(MemoryBasicInformation));

            var addr = min;
            do
            {
                MemoryBasicInformation mbi;
                if (WinAPI.VirtualQueryEx(process.Handle, (IntPtr)addr, out mbi, mbiSize) == (SizeT)0)
                    break;
                addr += (long)mbi.RegionSize;

                // don't care about reserved/free pages
                if (mbi.State != MemPageState.MEM_COMMIT)
                    continue;

                // probably don't care about guarded pages
                if (!all && (mbi.Protect & MemPageProtect.PAGE_GUARD) != 0)
                    continue;

                // probably don't care about image/file maps
                if (!all && mbi.Type != MemPageType.MEM_PRIVATE)
                    continue;

                yield return mbi;

            } while (addr < max);
        }

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

private IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

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

public static bool IsSessionActive(int sessionId)
		{
			bool isActive = false;
			try
			{
				IntPtr pSessions = IntPtr.Zero;
				int count = 0;
				if (wtsapi32.WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessions, ref count))
				{
					WTS_SESSION_INFO si = new WTS_SESSION_INFO();
					IntPtr pSession = pSessions;
					for (int i = 0; i < count; ++i)
					{
						//WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(pSession, typeof(WTS_SESSION_INFO));
						Marshal.PtrToStructure(pSession, si);
						pSession = new IntPtr(pSession.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
						if (si.SessionId == sessionId)
						{
							isActive = (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive);
							break;
						}
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return isActive;
		}

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

public static string[] GetLocalGroupMembers(string groupname)
		{
			int read;
			int total;
			int resume;
			IntPtr pbuf;

			int ret = netapi.NetLocalGroupGetMembers(null, groupname, 3, out pbuf, -1, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);

			List<string> members = new List<string>();
			if (read > 0)
			{
				var m = new LOCALGROUP_MEMBERS_INFO_3();
				IntPtr pItem = pbuf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, m);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_MEMBERS_INFO_3)));
					members.Add(DomainUser.Parse(m.domainandname).ToString());
				}
			}
			netapi.NetApiBufferFree(pbuf);
			return members.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 : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

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

public static IEnumerable<DomainUser> EnumLocalUsers(bool sid = false)
		{
			int read;
			int total;
			int resume;
			IntPtr buf;

			int ret = netapi.NetUserEnum(null, 10, util.FILTER_NORMAL_ACCOUNT, out buf, util.MAX_PREFERRED_LENGTH, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);
			if (read > 0)
			{
				DomainUser user = new DomainUser();
				var u = new USER_INFO_10();
				IntPtr pItem = buf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, u);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(USER_INFO_10)));

					if (sid)
						user.SID = GetAccountSID(u.name);
					user.Name = u.name;
					user.FullName = u.full_name;
					user.Comment = u.comment;
					yield return user;
				}
				netapi.NetApiBufferFree(buf);
			}
		}

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

public static string[] GetLocalUserGroups(string username)
		{
			int read;
			int total;
			IntPtr pbuf;

			int ret = netapi.NetUserGetLocalGroups(null, username, 0, 0, out pbuf, -1, out read, out total);
			if (ret != 0)
				throw new Win32Exception(ret);

			List<string> groups = new List<string>();
			if (read > 0)
			{
				var g = new LOCALGROUP_USERS_INFO_0();
				IntPtr pItem = pbuf;
				for (int i = 0; i < read; ++i)
				{
					Marshal.PtrToStructure(pItem, g);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_USERS_INFO_0)));
					groups.Add(g.name);
				}
			}
			netapi.NetApiBufferFree(pbuf);
			return groups.ToArray();
		}

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

private static IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

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

private static IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
		{
			int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
			IntPtr hTcpTable = IntPtr.Zero;
			{
				hTcpTable = Marshal.AllocHGlobal(dwSize);
				int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
				if (ret != util.NO_ERROR)
				{
					// retry for new dwSize.
					Marshal.FreeHGlobal(hTcpTable);
					hTcpTable = Marshal.AllocHGlobal(dwSize);
					ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
					if (ret != util.NO_ERROR)
					{
						Marshal.FreeHGlobal(hTcpTable);
						throw new Exception("GetExtendedTcpTable return: " + ret);
					}
				}
			}
			{
				MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
				int dwNumEntries = Marshal.ReadInt32(hTcpTable);
				IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
				for (int i = 0; i < dwNumEntries; ++i)
				{
					//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
					Marshal.PtrToStructure(pItem, item);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
					yield return item;
				}
				Marshal.FreeHGlobal(hTcpTable);
			}
		}

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

private static int OffsetFor<T>(int index) => index * Marshal.SizeOf(typeof(T));

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

private static IntPtr IncrementByStructSize<T>(IntPtr prev, T instance) => prev + Marshal.SizeOf(typeof(T));

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

internal 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))
				{
					WTS_SESSION_INFO si = new WTS_SESSION_INFO();
					IntPtr p = pSessions;
					for (int i = 0; i < count; ++i)
					{
						Marshal.PtrToStructure(p, si);
						if (si.State == WTS_CONNECTSTATE_CLreplaced.WTSActive)
							sessions.Add(si.SessionId);
						p = new IntPtr(p.ToInt64() + Marshal.SizeOf(typeof(WTS_SESSION_INFO)));
					}
					wtsapi32.WTSFreeMemory(pSessions);
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
			return sessions.ToArray();
		}

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

public static IEnumerable<DomainGroup> EnumLocalGroups(bool sid = false)
		{
			int read;
			int total;
			int resume;
			IntPtr buf;

			int ret = netapi.NetLocalGroupEnum(null, 1, out buf, util.MAX_PREFERRED_LENGTH, out read, out total, out resume);
			if (ret != 0)
				throw new Win32Exception(ret);
			if (read > 0)
			{
				DomainGroup group = new DomainGroup();
				var g = new LOCALGROUP_INFO_1();
				IntPtr pItem = buf;
				for (int i = 0; i < read; i++)
				{
					Marshal.PtrToStructure(pItem, g);
					pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(LOCALGROUP_INFO_1)));

					if (sid)
						group.SID = GetAccountSID(g.name);
					group.Name = g.name;
					group.Comment = g.comment;
					yield return group;
				}
				netapi.NetApiBufferFree(buf);
			}
		}

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

protected virtual void Update()
	{
		var system = OpenVR.System;
		if (system != null && system.GetControllerState(controllerIndex, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t))))
		{
			ulong trigger = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Trigger));
			if (trigger > 0L && !triggerPressed)
			{
				triggerPressed = true;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnTriggerClicked(e);

			}
			else if (trigger == 0L && triggerPressed)
			{
				triggerPressed = false;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnTriggerUnclicked(e);
			}

			ulong grip = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_Grip));
			if (grip > 0L && !gripped)
			{
				gripped = true;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnGripped(e);

			}
			else if (grip == 0L && gripped)
			{
				gripped = false;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnUngripped(e);
			}

			ulong pad = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Touchpad));
			if (pad > 0L && !padPressed)
			{
				padPressed = true;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnPadClicked(e);
			}
			else if (pad == 0L && padPressed)
			{
				padPressed = false;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnPadUnclicked(e);
			}

			ulong menu = controllerState.ulButtonPressed & (1UL << ((int)EVRButtonId.k_EButton_ApplicationMenu));
			if (menu > 0L && !menuPressed)
			{
				menuPressed = true;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnMenuClicked(e);
			}
			else if (menu == 0L && menuPressed)
			{
				menuPressed = false;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnMenuUnclicked(e);
			}

			pad = controllerState.ulButtonTouched & (1UL << ((int)EVRButtonId.k_EButton_SteamVR_Touchpad));
			if (pad > 0L && !padTouched)
			{
				padTouched = true;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnPadTouched(e);

			}
			else if (pad == 0L && padTouched)
			{
				padTouched = false;
				ClickedEventArgs e;
				e.controllerIndex = controllerIndex;
				e.flags = (uint)controllerState.ulButtonPressed;
				e.padX = controllerState.rAxis0.x;
				e.padY = controllerState.rAxis0.y;
				OnPadUntouched(e);
			}
		}
	}

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);
	}

See More Examples