예제 #1
0
파일: Usb.cs 프로젝트: zzattack/zektor
        /// <summary>
        ///     Registers to be notified when devices are added or removed.
        /// </summary>
        /// <param name="register">True to register, False to unregister</param>
        /// <param name="f">Form</param>
        /// <returns>True if successfull, False otherwise</returns>
        public bool RegisterForDeviceChange(bool doRegister, Form f)
        {
            var  Status = false;
            long LastError;

            if (doRegister)
            {
                var deviceInterface = new Win32Wrapper.DEV_BROADCAST_DEVICEINTERFACE();
                int size            = Marshal.SizeOf(deviceInterface);
                deviceInterface.dbcc_size       = size;
                deviceInterface.dbcc_devicetype = (int)Win32Wrapper.DBTDEVTYP.DBT_DEVTYP_DEVICEINTERFACE;
                var buffer = default(IntPtr);
                buffer = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(deviceInterface, buffer, true);
                deviceEventHandle = Win32Wrapper.RegisterDeviceNotification(f.Handle, buffer,
                                                                            (int)(Win32Wrapper.DEVICE_NOTIFY.DEVICE_NOTIFY_WINDOW_HANDLE | Win32Wrapper.DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES));
                Status = deviceEventHandle != IntPtr.Zero;
                if (!Status)
                {
                    LastError = Marshal.GetLastWin32Error();
                }
                Marshal.FreeHGlobal(buffer);
            }
            else
            {
                if (deviceEventHandle != IntPtr.Zero)
                {
                    Status = Win32Wrapper.UnregisterDeviceNotification(deviceEventHandle);
                }
                deviceEventHandle = IntPtr.Zero;
            }

            return(Status);
        }
예제 #2
0
        private static string ShowVagrantFolderBrowser(Window parentWindow, string initialPath = "")
        {
            var winWrapper = new Win32Wrapper(parentWindow);

            var folderDialog = new FolderBrowserDialog();

            folderDialog.Description         = "Select Vagrant Folder";
            folderDialog.ShowNewFolderButton = false;
            folderDialog.RootFolder          = Environment.SpecialFolder.MyComputer;
            if (!initialPath.Equals(String.Empty))
            {
                folderDialog.SelectedPath = initialPath;
            }


            if (folderDialog.ShowDialog(winWrapper) == DialogResult.OK)
            {
                if (!File.Exists(Path.Combine(folderDialog.SelectedPath, "Vagrantfile")))
                {
                    MessageBox.Show(winWrapper,
                                    "The folder you have selected is not a valid Vagrant folder. Please try again.");
                    return(String.Empty);
                }
            }
            return(folderDialog.SelectedPath);
        }
예제 #3
0
        private async void PasteFromClipboard(TextItem textItem)
        {
            try
            {
                if (textItem == null)
                {
                    return;
                }

                _window.HideWithPrevStatePreserved();

                await System.Threading.Tasks.Task.Run(() => System.Threading.Thread.Sleep(200));

                IntPtr targetWindow = await Win32Wrapper.PasteText(textItem.Text, KeepOnClipboardAfterInsert);

                _window.ShowWithPreservedState();

                Win32Wrapper.SetForegroundWindow(targetWindow);
            }
            catch (Exception ex)
            {
                string error = Localization.TranslationManager.Instance.TranslateString("ErrorMessagePasterFromClipboard");
                LogHelper.LogException(ex, error);
                _confirmer.ConfirmStop(error);
            }
        }
예제 #4
0
        public bool RegisterForDeviceChange(bool Register, IntPtr WindowsHandle)
        {
            var flag = false;

            if (Register)
            {
                var structure = new USBClass.Win32Wrapper.DEV_BROADCAST_DEVICEINTERFACE();
                var cb        = Marshal.SizeOf <USBClass.Win32Wrapper.DEV_BROADCAST_DEVICEINTERFACE>(structure);
                structure.dbcc_size       = cb;
                structure.dbcc_devicetype = 5;
                var    num1 = new IntPtr();
                IntPtr num2 = Marshal.AllocHGlobal(cb);
                Marshal.StructureToPtr <USBClass.Win32Wrapper.DEV_BROADCAST_DEVICEINTERFACE>(structure, num2, true);
                deviceEventHandle = Win32Wrapper.RegisterDeviceNotification(WindowsHandle, num2, 4);
                flag = deviceEventHandle != IntPtr.Zero;
                if (!flag)
                {
                    Marshal.GetLastWin32Error();
                }

                Marshal.FreeHGlobal(num2);
            }
            else
            {
                if (deviceEventHandle != IntPtr.Zero)
                {
                    flag = Win32Wrapper.UnregisterDeviceNotification(deviceEventHandle);
                }

                deviceEventHandle = IntPtr.Zero;
            }
            return(flag);
        }
예제 #5
0
 static void PrintVisibleWindowHandles(int maxLevel = -1)
 {
     // Enumerates all existing top window handles. This includes open and visible windows, as well as invisible windows.
     Win32Wrapper.EnumWindows(new Win32Wrapper.EnumWindowsProc((tophandle, topparamhandle) =>
     {
         PrintVisibleWindowHandles(tophandle, maxLevel);
         return(true);
     }), IntPtr.Zero);
 }
예제 #6
0
        private void PerformHotSampling()
        {
            if (_newWidthBox.Value < 100 || _newHeightBox.Value < 100)
            {
                return;
            }
            if ((Win32Wrapper.IsIconic(_gameWindowHwnd) || Win32Wrapper.IsZoomed(_gameWindowHwnd)))
            {
                Win32Wrapper.ShowWindow(_gameWindowHwnd, Win32Wrapper.SW_SHOWNOACTIVATE);
            }

            int newHorizontalResolution = (int)_newWidthBox.Value;
            int newVerticalResolution   = (int)_newHeightBox.Value;
            // always set the window at (0,0), if width is >= screen width.
            var  screenBounds = Screen.FromHandle(_gameWindowHwnd).Bounds;
            uint uFlags       = Win32Wrapper.SWP_NOZORDER | Win32Wrapper.SWP_NOACTIVATE | Win32Wrapper.SWP_NOOWNERZORDER | Win32Wrapper.SWP_NOSENDCHANGING;

            if (newHorizontalResolution < screenBounds.Width)
            {
                // let the window be where it is.
                uFlags |= Win32Wrapper.SWP_NOMOVE;
            }

            Win32Wrapper.SetWindowPos(_gameWindowHwnd, 0, 0, 0, newHorizontalResolution, newVerticalResolution, uFlags);
            if (GameSpecificConstants.HotsamplingRequiresEXITSIZEMOVE)
            {
                // A warning of unreachable code will be raised here, that's ok. this code is only used when the constant is true
                Win32Wrapper.SendMessage(_gameWindowHwnd, Win32Wrapper.WM_EXITSIZEMOVE, 0, 0);
            }

            LogHandlerSingleton.Instance().LogLine("Switching resolution on window with hwnd 0x{0} to resolution {1}x{2}", "Hotsampler", _gameWindowHwnd.ToString("x"),
                                                   newHorizontalResolution, newVerticalResolution);

            // remove / add borders
            uint nStyle = (uint)Win32Wrapper.GetWindowLong(_gameWindowHwnd, Win32Wrapper.GWL_STYLE);

            nStyle = (nStyle | (Win32Wrapper.WS_THICKFRAME + Win32Wrapper.WS_DLGFRAME + Win32Wrapper.WS_BORDER + Win32Wrapper.WS_MAXIMIZEBOX + Win32Wrapper.WS_MINIMIZEBOX));
            if (_useWindowBordersCheckBox.IsChecked == false)
            {
                nStyle ^= (Win32Wrapper.WS_THICKFRAME + Win32Wrapper.WS_DLGFRAME + Win32Wrapper.WS_BORDER + Win32Wrapper.WS_MAXIMIZEBOX + Win32Wrapper.WS_MINIMIZEBOX);
            }
            Win32Wrapper.SetWindowLong(_gameWindowHwnd, Win32Wrapper.GWL_STYLE, nStyle);
            uFlags = Win32Wrapper.SWP_NOSIZE | Win32Wrapper.SWP_NOMOVE | Win32Wrapper.SWP_NOZORDER | Win32Wrapper.SWP_NOACTIVATE | Win32Wrapper.SWP_NOOWNERZORDER | Win32Wrapper.SWP_NOSENDCHANGING | Win32Wrapper.SWP_FRAMECHANGED;
            Win32Wrapper.SetWindowPos(_gameWindowHwnd, 0, 0, 0, 0, 0, uFlags);

            // Send the resize viewport message to the dll so it can resize the viewport based on the new resolution. The game itself won't resize the viewport on its own.
            MessageHandlerSingleton.Instance().SendResizeViewportAction(newHorizontalResolution, newVerticalResolution);

            AddResolutionToRecentlyUsedList(newHorizontalResolution, newVerticalResolution);

            if (_switchAfterResizingCheckBox.IsChecked == true)
            {
                // focus the attached application's window
                Win32Wrapper.SetForegroundWindow(_gameWindowHwnd);
            }
        }
예제 #7
0
        public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                _window.KeyEventHandler((Win32Wrapper.KeyMessages)wParam, (int)wParam, vkCode);
            }

            return(Win32Wrapper.CallNextHookEx(_hookID, nCode, wParam, lParam));
        }
        private static int FindPortByWinMsg()
        {
            //Start message queue
            Win32Wrapper.PeekMessage(out Win32Wrapper.NativeMessage msg, 0, (uint)0x600, (uint)0x600, Win32Wrapper.PM_REMOVE);

            Trace.WriteLine("Prepare message for Stealth", "Stealth.Main");
            var procstring = Process.GetCurrentProcess().Id.ToString("X8") + Process.GetCurrentProcess().MainModule.FileName.Replace(".vshost", "") + '\0';

            Trace.WriteLine(string.Format("Procstring: {0}", procstring), "Stealth.Main");
            var aCopyData = new Win32Wrapper.CopyDataStruct
            {
                dwData = (uint)Win32Wrapper.GetCurrentThreadId(),
                cbData = Process.GetCurrentProcess().MainModule.FileName.Replace(".vshost", "").Length + 8 + 1,
                lpData = Marshal.StringToHGlobalAnsi(procstring)
            };

            IntPtr copyDataPtr = aCopyData.MarshalToPtr();

            try
            {
                Trace.WriteLine("Find Stealth window", "Stealth.Main");
                IntPtr tWndPtr = Win32Wrapper.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "TStealthForm", null);
                if (tWndPtr != IntPtr.Zero)
                {
                    Trace.WriteLine("Stealth window found. Send message.", "Stealth.Main");
                    IntPtr ret = Win32Wrapper.SendMessage(tWndPtr, Win32Wrapper.WM_COPYDATA, IntPtr.Zero, copyDataPtr);
                    Trace.WriteLine("Message sended. Wait message from Stealth.", "Stealth.Main");
                    while (!Win32Wrapper.PeekMessage(out msg, 0, (uint)0x600, (uint)0x600, Win32Wrapper.PM_REMOVE))
                    {
                        Thread.Sleep(10);
                    }
                    Trace.WriteLine(string.Format("Message recieved. Port: {0}", (int)(msg.wParam)), "Stealth.Main");
                }
                else
                {
                    throw new InvalidOperationException("Could not attach to Stealth. Exiting.");
                }
            }
            catch (InvalidOperationException)
            {
                return(-1);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex, "Stealth.Main");
                return(-1);
            }
            finally
            {
                Marshal.FreeHGlobal(copyDataPtr);
            }

            return((int)(msg.wParam));
        }
예제 #9
0
        private void RepositionWindow(int newX, int newY)
        {
            if (_gameWindowHwnd == IntPtr.Zero)
            {
                return;
            }
            if ((Win32Wrapper.IsIconic(_gameWindowHwnd) || Win32Wrapper.IsZoomed(_gameWindowHwnd)))
            {
                Win32Wrapper.ShowWindow(_gameWindowHwnd, Win32Wrapper.SW_SHOWNOACTIVATE);
            }
            uint uFlags = Win32Wrapper.SWP_NOSIZE | Win32Wrapper.SWP_NOZORDER | Win32Wrapper.SWP_NOACTIVATE | Win32Wrapper.SWP_NOOWNERZORDER | Win32Wrapper.SWP_NOSENDCHANGING | Win32Wrapper.SWP_FRAMECHANGED;

            Win32Wrapper.SetWindowPos(_gameWindowHwnd, 0, newX, newY, 0, 0, uFlags);
        }
예제 #10
0
        public static IntPtr SetHook(Win32Wrapper.LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
                using (ProcessModule curModule = curProcess.MainModule)
                {
                    return(Win32Wrapper.SetWindowsHookEx((int)Win32Wrapper.HookType.WH_KEYBOARD_LL, proc,
                                                         Win32Wrapper.GetModuleHandle(curModule.ModuleName), 0));
                }

            //IntPtr hwndWorkerW = IntPtr.Zero;
            //IntPtr hShellDefView = IntPtr.Zero;
            //IntPtr hwndDesktop = IntPtr.Zero;

            //IntPtr hProgMan = Win32Wrapper.FindWindow("ProgMan", null);
            //Win32Wrapper.EnumWindows(new Win32Wrapper.EnumWindowsProc((tophandle, topparamhandle) =>
            //{
            //    IntPtr p = Win32Wrapper.FindWindowEx(tophandle,
            //                                IntPtr.Zero,
            //                                "SHELLDLL_DefView",
            //                                null);

            //    if (p != IntPtr.Zero)
            //    {
            //        // Gets the WorkerW Window after the current one.
            //        hwndWorkerW = Win32Wrapper.FindWindowEx(IntPtr.Zero,
            //                                   tophandle,
            //                                   "WorkerW",
            //                                   null);

            //        hwndDesktop = Win32Wrapper.FindWindowEx(p,
            //                                    IntPtr.Zero,
            //                                   "SysListView32",
            //                                   null);
            //        return false;
            //    }
            //    return true;
            //}), IntPtr.Zero);

            //using (Process curProcess = Process.GetCurrentProcess())
            //using (ProcessModule curModule = curProcess.MainModule)
            //{
            //    return Win32Wrapper.SetWindowsHookEx((int)Win32Wrapper.HookType.WH_KEYBOARD_LL, proc,
            //        Win32Wrapper.GetModuleHandle(curModule.ModuleName), Win32Wrapper.GetWindowThreadProcessId(hwndDesktop, IntPtr.Zero));
            //}
        }
예제 #11
0
파일: Program.cs 프로젝트: peterM/RunAs
        static void Main(string[] args)
        {
            //Example:
            // "C:\Windows\System32\dsa.msc /domain=something.local"
            if (args.Length >= 4)
            {
                _settings.UserName = args[0];
                _settings.Domain   = args[1];
                _settings.Password = args[2];
                _settings.Command  = args[3];

                if (args.Length == 7)
                {
                    _settings.UseCustomCommandExecutor = bool.Parse(args[4]);
                    _settings.CustomCommandExecutor    = args[5];
                    _settings.CommandArgument          = args[6];
                }
            }

            StartupInfo startupInfo = new StartupInfo
            {
                cb    = Marshal.SizeOf(typeof(StartupInfo)),
                title = $"Impersonated command prompt - [{_settings.Domain}\\{_settings.UserName}]"
            };

            RunAsContext runAsContext = SetupRunAsContext(_settings);

            ProcessInfo processInfo = new ProcessInfo();

            if (Win32Wrapper.CreateProcessWithLogonW(_settings.UserName, _settings.Domain, _settings.Password, LogonFlags.LOGON_NETCREDENTIALS_ONLY, runAsContext.Executor, runAsContext.Command, 0, IntPtr.Zero, null, ref startupInfo, out processInfo))
            {
                Win32Wrapper.CloseHandle(processInfo.hProcess);
                Win32Wrapper.CloseHandle(processInfo.hThread);
            }
            else
            {
                string errorString = Marshal.GetLastWin32Error().ToString();
                Console.WriteLine(errorString);

                Console.WriteLine("\n\nPress any key to continue...");
                Console.ReadKey();
            }
        }
예제 #12
0
        private void PerformHotSampling()
        {
            if (_newWidthUpDown.Value < 100 || _newHeightUpDown.Value < 100)
            {
                return;
            }
            if ((Win32Wrapper.IsIconic(_gameWindowHwnd) || Win32Wrapper.IsZoomed(_gameWindowHwnd)))
            {
                Win32Wrapper.ShowWindow(_gameWindowHwnd, Win32Wrapper.SW_SHOWNOACTIVATE);
            }

            int newHorizontalResolution = (int)_newWidthUpDown.Value;
            int newVerticalResolution   = (int)_newHeightUpDown.Value;
            // always set the window at (0,0), if width is >= screen width.
            var  screenBounds = Screen.FromHandle(_gameWindowHwnd).Bounds;
            uint uFlags       = Win32Wrapper.SWP_NOZORDER | Win32Wrapper.SWP_NOACTIVATE | Win32Wrapper.SWP_NOOWNERZORDER | Win32Wrapper.SWP_NOSENDCHANGING;

            if (newHorizontalResolution < screenBounds.Width)
            {
                // let the window be where it is.
                uFlags |= Win32Wrapper.SWP_NOMOVE;
            }

            Win32Wrapper.SetWindowPos(_gameWindowHwnd, 0, 0, 0, newHorizontalResolution, newVerticalResolution, uFlags);
            if (GameSpecificConstants.HotsamplingRequiresEXITSIZEMOVE)
            {
                // A warning of unreachable code will be raised here, that's ok. this code is only used when the constant is true
                Win32Wrapper.SendMessage(_gameWindowHwnd, Win32Wrapper.WM_EXITSIZEMOVE, 0, 0);
            }

            // remove / add borders
            uint nStyle = (uint)Win32Wrapper.GetWindowLong(_gameWindowHwnd, Win32Wrapper.GWL_STYLE);

            nStyle = (nStyle | (Win32Wrapper.WS_THICKFRAME + Win32Wrapper.WS_DLGFRAME + Win32Wrapper.WS_BORDER + Win32Wrapper.WS_MAXIMIZEBOX + Win32Wrapper.WS_MINIMIZEBOX));
            if (!_useWindowBordersCheckBox.Checked)
            {
                nStyle ^= (Win32Wrapper.WS_THICKFRAME + Win32Wrapper.WS_DLGFRAME + Win32Wrapper.WS_BORDER + Win32Wrapper.WS_MAXIMIZEBOX + Win32Wrapper.WS_MINIMIZEBOX);
            }
            Win32Wrapper.SetWindowLong(_gameWindowHwnd, Win32Wrapper.GWL_STYLE, nStyle);
            uFlags = Win32Wrapper.SWP_NOSIZE | Win32Wrapper.SWP_NOMOVE | Win32Wrapper.SWP_NOZORDER | Win32Wrapper.SWP_NOACTIVATE | Win32Wrapper.SWP_NOOWNERZORDER | Win32Wrapper.SWP_NOSENDCHANGING | Win32Wrapper.SWP_FRAMECHANGED;
            Win32Wrapper.SetWindowPos(_gameWindowHwnd, 0, 0, 0, 0, 0, uFlags);
        }
예제 #13
0
 private void GetActiveGameWindowInfo()
 {
     _gameWindowHwnd = AppStateSingleton.Instance().GetMainWindowHandleOfAttachedProcess();
     if (_gameWindowHwnd == IntPtr.Zero)
     {
         _currentWidthTextBox.Text  = string.Empty;
         _currentHeightTextBox.Text = string.Empty;
         _currentARTextBox.Text     = string.Empty;
         return;
     }
     Win32Wrapper.GetWindowInfo(_gameWindowHwnd, ref _gameWindowInfo);
     _currentWidthTextBox.Text  = _gameWindowInfo.rcWindow.Width.ToString();
     _currentHeightTextBox.Text = _gameWindowInfo.rcWindow.Height.ToString();
     _currentARTextBox.Text     = GeneralUtils.CalculateAspectRatio(_gameWindowInfo.rcWindow.Width, _gameWindowInfo.rcWindow.Height).ToString(appendDescription: false);
     if (_newHeightBox.Value <= 0 || _newWidthBox.Value <= 0)
     {
         //reset with current window
         _newHeightBox.Value      = _gameWindowInfo.rcWindow.Height;
         _newWidthBox.Value       = _gameWindowInfo.rcWindow.Width;
         _aspectRatioTextBox.Text = _currentARTextBox.Text;
     }
 }
예제 #14
0
 private void GetActiveGameWindowInfo()
 {
     _gameWindowHwnd = AppStateSingleton.Instance().GetMainWindowHandleOfAttachedProcess();
     _currentResolutionGroupBox.Enabled = _gameWindowHwnd != IntPtr.Zero;
     if (_gameWindowHwnd == IntPtr.Zero)
     {
         _currentWidthTextBox.Text  = string.Empty;
         _currentHeightTextBox.Text = string.Empty;
         _currentARTextBox.Text     = string.Empty;
         return;
     }
     Win32Wrapper.GetWindowInfo(_gameWindowHwnd, ref _gameWindowInfo);
     _currentWidthTextBox.Text  = _gameWindowInfo.rcWindow.Width.ToString();
     _currentHeightTextBox.Text = _gameWindowInfo.rcWindow.Height.ToString();
     _currentARTextBox.Text     = CalculateAspectRatio(_gameWindowInfo.rcWindow.Width, _gameWindowInfo.rcWindow.Height).ToString();
     if (_newHeightUpDown.Value <= 0 || _newWidthUpDown.Value <= 0)
     {
         //reset with current window
         _newHeightUpDown.Value = _gameWindowInfo.rcWindow.Height;
         _newWidthUpDown.Value  = _gameWindowInfo.rcWindow.Width;
     }
 }
예제 #15
0
        static void PrintVisibleWindowHandles(IntPtr hwnd, int maxLevel = -1, int level = 0)
        {
            bool isVisible = Win32Wrapper.IsWindowVisible(hwnd);

            if (isVisible && (maxLevel == -1 || level <= maxLevel))
            {
                StringBuilder className = new StringBuilder(256);
                Win32Wrapper.GetClassName(hwnd, className, className.Capacity);

                StringBuilder windowTitle = new StringBuilder(256);
                Win32Wrapper.GetWindowText(hwnd, windowTitle, className.Capacity);

                Console.WriteLine("".PadLeft(level * 2) + "0x{0:X8} \"{1}\" {2}", hwnd.ToInt64(), windowTitle, className);

                level++;

                // Enumerates all child windows of the current window
                Win32Wrapper.EnumChildWindows(hwnd, new Win32Wrapper.EnumWindowsProc((childhandle, childparamhandle) =>
                {
                    PrintVisibleWindowHandles(childhandle, maxLevel, level);
                    return(true);
                }), IntPtr.Zero);
            }
        }
예제 #16
0
 private void _switchToGameWindowButton_OnClick(object sender, RoutedEventArgs e)
 {
     // focus the attached application's window
     Win32Wrapper.SetForegroundWindow(_gameWindowHwnd);
 }
예제 #17
0
 private void ResizeGripPreviewMouseDown(object sender, MouseButtonEventArgs e)
 {
     Win32Wrapper.ResizeWindow(_windowHandle, Win32Wrapper.ResizeDirection.Right);
 }
예제 #18
0
        public static bool GetUSBDevice(uint VID, uint PID, List <USBClass.DeviceProperties> DPList, bool GetCOMPort, uint?MI = null)
        {
            IntPtr num1 = Marshal.AllocHGlobal(1024);
            IntPtr num2 = IntPtr.Zero;

            DPList.Clear();
            try
            {
                var Enumerator      = "USB";
                var empty           = string.Empty;
                var str             = string.Empty;
                var lowerInvariant1 = ("VID_" + VID.ToString("X4") + "&PID_" + PID.ToString("X4")).ToLowerInvariant();
                if (MI.HasValue)
                {
                    str = ("MI_" + MI.Value.ToString("X2")).ToLowerInvariant();
                }

                num2 = Win32Wrapper.SetupDiGetClassDevs(IntPtr.Zero, Enumerator, IntPtr.Zero, 6);
                if (num2.ToInt64() != -1L)
                {
                    var  flag        = true;
                    uint MemberIndex = 0;
                    while (flag)
                    {
                        if (flag)
                        {
                            uint RequiredSize        = 0;
                            uint PropertyRegDataType = 0;
                            var  DeviceInfoData      = new USBClass.Win32Wrapper.SP_DEVINFO_DATA();
                            DeviceInfoData.cbSize = (uint)Marshal.SizeOf <USBClass.Win32Wrapper.SP_DEVINFO_DATA>(DeviceInfoData);
                            flag = Win32Wrapper.SetupDiEnumDeviceInfo(num2, MemberIndex, ref DeviceInfoData);
                            if (flag)
                            {
                                Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 1U, ref PropertyRegDataType, IntPtr.Zero, 0U, ref RequiredSize);
                                if (Marshal.GetLastWin32Error() == 122 && RequiredSize <= 1024U && Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 1U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                {
                                    var lowerInvariant2 = Marshal.PtrToStringAuto(num1).ToLowerInvariant();
                                    if (lowerInvariant2.Contains(lowerInvariant1) && (MI.HasValue && lowerInvariant2.Contains(str) || !MI.HasValue && !lowerInvariant2.Contains("mi")))
                                    {
                                        var deviceProperties = new DeviceProperties
                                        {
                                            FriendlyName = string.Empty
                                        };
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 12U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.FriendlyName = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DeviceType = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 25U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DeviceType = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DeviceClass = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 7U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DeviceClass = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DeviceManufacturer = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 11U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DeviceManufacturer = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DeviceLocation = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 13U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DeviceLocation = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DevicePath = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 35U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DevicePath = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DevicePhysicalObjectName = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 14U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DevicePhysicalObjectName = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.DeviceDescription = string.Empty;
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(num2, ref DeviceInfoData, 0U, ref PropertyRegDataType, num1, 1024U, ref RequiredSize))
                                        {
                                            deviceProperties.DeviceDescription = Marshal.PtrToStringAuto(num1);
                                        }

                                        deviceProperties.COMPort = string.Empty;
                                        if (GetCOMPort)
                                        {
                                            IntPtr hKey = Win32Wrapper.SetupDiOpenDevRegKey(num2, ref DeviceInfoData, 1U, 0U, 1U, 131097U);
                                            if (hKey.ToInt32() == -1)
                                            {
                                                deviceProperties.COMPort = null;
                                            }
                                            else
                                            {
                                                var lpData   = new StringBuilder(1024);
                                                var capacity = (uint)lpData.Capacity;
                                                if (Win32Wrapper.RegQueryValueEx(hKey, "PortName", 0U, out var lpType, lpData, ref capacity) == 0)
                                                {
                                                    deviceProperties.COMPort = lpData.ToString();
                                                }

                                                Win32Wrapper.RegCloseKey(hKey);
                                            }
                                        }
                                        DPList.Add(deviceProperties);
                                    }
                                }
                            }
                        }
                        else
                        {
                            var lastWin32Error = (long)Marshal.GetLastWin32Error();
                        }
                        ++MemberIndex;
                    }
                }
                return(DPList.Count > 0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Win32Wrapper.SetupDiDestroyDeviceInfoList(num2);
                Marshal.FreeHGlobal(num1);
            }
        }
예제 #19
0
        public static void SetDesktopAsParent(IntPtr handle)
        {
            PrintVisibleWindowHandles(2);
            // The output will look something like this.
            // .....
            // 0x00010190 "" WorkerW
            //   ...
            //   0x000100EE "" SHELLDLL_DefView
            //     0x000100F0 "FolderView" SysListVieWin32Wrapper
            // 0x000100EC "Program Manager" Progman



            // Fetch the Progman window
            IntPtr progman = Win32Wrapper.FindWindow("Progman", null);

            IntPtr result = IntPtr.Zero;

            // Send 0x052C to Progman. This message directs Progman to spawn a
            // WorkerW behind the desktop icons. If it is already there, nothing
            // happens.
            Win32Wrapper.SendMessageTimeout(progman,
                                            0x052C,
                                            new IntPtr(0),
                                            IntPtr.Zero,
                                            Win32Wrapper.SendMessageTimeoutFlags.SMTO_NORMAL,
                                            1000,
                                            out result);


            PrintVisibleWindowHandles(2);
            // The output will look something like this
            // .....
            // 0x00010190 "" WorkerW
            //   ...
            //   0x000100EE "" SHELLDLL_DefView
            //     0x000100F0 "FolderView" SysListVieWin32Wrapper
            // 0x00100B8A "" WorkerW                                   <--- This is the WorkerW instance we are after!
            // 0x000100EC "Program Manager" Progman

            // We enumerate all Windows, until we find one, that has the SHELLDLL_DefView
            // as a child.
            // If we found that window, we take its next sibling and assign it to workerw.
            Win32Wrapper.EnumWindows(new Win32Wrapper.EnumWindowsProc((tophandle, topparamhandle) =>
            {
                IntPtr p = Win32Wrapper.FindWindowEx(tophandle,
                                                     IntPtr.Zero,
                                                     "SHELLDLL_DefView",
                                                     null);

                if (p != IntPtr.Zero)
                {
                    // Gets the WorkerW Window after the current one.
                    _workerw = Win32Wrapper.FindWindowEx(IntPtr.Zero,
                                                         tophandle,
                                                         "WorkerW",
                                                         null);
                    return(false);
                }

                return(true);
            }), IntPtr.Zero);

            Win32Wrapper.SetParent(handle, _workerw);
        }