Exemplo n.º 1
0
        /// <summary>
        /// Gets the selected text of the given window, or the last activate window.
        /// </summary>
        /// <param name="sendKeys">The <c>SendKeys.SendWait</c> method.</param>
        /// <param name="windowHandle">The window.</param>
        /// <returns>The selected text.</returns>
        public async Task GetSelectedText(Action <string> sendKeys, IntPtr?windowHandle = null)
        {
            IntPtr hwnd = windowHandle ?? this.lastWindow;
            await Task.Run(() =>
            {
                if (hwnd != IntPtr.Zero)
                {
                    // Activate the window, if it's not already.
                    IntPtr active = WindowsApi.GetForegroundWindow();
                    if (active != hwnd)
                    {
                        this.gotActiveWindow.Reset();
                        WindowsApi.SetForegroundWindow(hwnd);

                        // Wait for it to be activated.
                        this.gotActiveWindow.WaitOne(3000);
                    }
                }

                // Copy the selected text to clipboard
                this.gotClipboard.Reset();
                sendKeys("^c");

                // Wait for the clipboard update.
                this.gotClipboard.WaitOne(3000);
            });

            return;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets or sets the current value of filter keys setting.
        /// </summary>
        /// <param name="newvalue"></param>
        /// <returns></returns>
        public static bool KeyRepeat(bool?newvalue = null)
        {
            WindowsApi.FILTERKEYS filterKeys = new WindowsApi.FILTERKEYS
            {
                cbSize = Marshal.SizeOf <WindowsApi.FILTERKEYS>()
            };

            WindowsApi.SystemParametersInfoFilterKeys(
                WindowsApi.SPI_GETFILTERKEYS, filterKeys.cbSize, ref filterKeys, 0);

            if (newvalue != null)
            {
                if (newvalue == true)
                {
                    filterKeys.dwFlags |= WindowsApi.FILTERKEYS.FKF_FILTERKEYSON;
                }
                else
                {
                    filterKeys.dwFlags &= ~WindowsApi.FILTERKEYS.FKF_FILTERKEYSON;
                }

                WindowsApi.SystemParametersInfoFilterKeys(
                    WindowsApi.SPI_SETFILTERKEYS, filterKeys.cbSize, ref filterKeys, 3);
            }

            return((filterKeys.dwFlags & WindowsApi.FILTERKEYS.FKF_FILTERKEYSON)
                   == WindowsApi.FILTERKEYS.FKF_FILTERKEYSON);
        }
Exemplo n.º 3
0
        public static ProcessorArchitecture?GetProcessorArchitecture()
        {
            // var cSystemInfo = new WindowsApi.SYSTEM_INFO();
            WindowsApi.SYSTEM_INFO cSystemInfo;
            WindowsApi.GetSystemInfo(out cSystemInfo);

            switch (cSystemInfo.dummyUnion.DUMMYSTRUCTNAME.wProcessorArchitecture)
            {
            case (UInt16)WindowsApi.ProcessorArchitecture.IA32:
                return(ProcessorArchitecture.X86);

            case (UInt16)WindowsApi.ProcessorArchitecture.ARM:
                return(ProcessorArchitecture.Arm32);

            //case 6: // PROCESSOR_ARCHITECTURE_IA64
            //    return ProcessorArchitecture.Itanium;
            case (UInt16)WindowsApi.ProcessorArchitecture.AMD64:
                return(ProcessorArchitecture.X64);

            //case 11:
            //    return ProcessorArchitecture.Neutral;
            case (UInt16)WindowsApi.ProcessorArchitecture.ARM64:
                return(ProcessorArchitecture.Arm64);

            //case 14:
            //    // NOTE: in our tests, x86 emulation on ARM64 just returned "PROCESSOR_ARCHITECTURE_INTEL" (0)
            //    return ProcessorArchitecture.X86;
            case (UInt16)WindowsApi.ProcessorArchitecture.UNKNOWN:
            default:
                return(null);
            }
        }
Exemplo n.º 4
0
 public void Initialise(IntPtr hwnd)
 {
     if (this.shellMessage == 0)
     {
         this.shellMessage = WindowsApi.RegisterWindowMessage("SHELLHOOK");
         WindowsApi.RegisterShellHookWindow(hwnd);
         WindowsApi.AddClipboardFormatListener(hwnd);
     }
 }
Exemplo n.º 5
0
        public void DeleteKey(String key, String section)
        {
            var success = WindowsApi.WritePrivateProfileString(section, key, null, _path);

            if (success == false)
            {
                var hresult = Marshal.GetHRForLastWin32Error();
                throw Marshal.GetExceptionForHR(hresult);
            }
        }
Exemplo n.º 6
0
        public void ClearSection(String section)
        {
            var success = WindowsApi.WritePrivateProfileSection(section, "", _path);

            if (success == false)
            {
                var hresult = Marshal.GetHRForLastWin32Error();
                throw Marshal.GetExceptionForHR(hresult);
            }
        }
Exemplo n.º 7
0
        public static Boolean?GetMouseButtonsAreSwapped()
        {
            // first, make sure that a mouse is present
            if (Mouse.GetMouseIsPresent() == false)
            {
                return(null);
            }

            var mouseButtonsAreSwapped = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_SWAPBUTTON);

            return(mouseButtonsAreSwapped != 0 ? true : false);
        }
        public static List <DisplayAdapterMonitorInfo> GetAllMonitorsForDisplayAdapter(String displayAdapterName)
        {
            var result = new List <DisplayAdapterMonitorInfo>();

            var displayAdapterNameAsCharArray = ConvertStringToNullTerminatedCharArray(displayAdapterName);

            // get the monitors associated with this display adapter
            UInt32 iMonitor = 0;
            //
            var success = true;

            while (success == true)
            {
                var cDisplayDevice = new WindowsApi.DISPLAY_DEVICEW();
                cDisplayDevice.Init();

                success = WindowsApi.EnumDisplayDevices_Monitor(displayAdapterNameAsCharArray, iMonitor, ref cDisplayDevice, 0);
                if (success == false)
                {
                    break;
                }

                var monitorDeviceNameAsString   = Display.ConvertCharArrayToString(cDisplayDevice.DeviceName);
                var monitorDeviceStringAsString = Display.ConvertCharArrayToString(cDisplayDevice.DeviceString);
                var monitorStateFlags           = (UInt32)cDisplayDevice.StateFlags;

                Boolean isAttached = false;
                if ((monitorStateFlags & (UInt32)WindowsApi.ChildDisplayDeviceStateFlags.DISPLAY_DEVICE_ATTACHED) != 0)
                {
                    isAttached = true;
                }
                // if the monitor is not attached, do not include it in the enumeration; we may modify this logic in the future if/as desired
                if (isAttached == false)
                {
                    iMonitor += 1;
                    continue;
                }

                Boolean isActive = false;
                if ((monitorStateFlags & (UInt32)WindowsApi.ChildDisplayDeviceStateFlags.DISPLAY_DEVICE_ACTIVE) != 0)
                {
                    isActive = true;
                }

                var monitorInfo = new DisplayAdapterMonitorInfo(monitorDeviceNameAsString, monitorDeviceStringAsString, isActive);

                result.Add(monitorInfo);

                iMonitor += 1;
            }

            return(result);
        }
        public static UInt32?GetDpiForWindow(IntPtr handle)
        {
            var dpiForWindow = WindowsApi.GetDpiForWindow(handle);

            if (dpiForWindow == 0)
            {
                return(null);
            }
            else
            {
                return(dpiForWindow);
            }
        }
        //
        //public static Size? GetMainDisplayMonitorSizeInPixels_DpiAware(UInt32 dpi)
        //{
        //    var width = WindowsApi.GetSystemMetricsForDpi(WindowsApi.SystemMetricIndex.SM_CXSCREEN, dpi);
        //    var height = WindowsApi.GetSystemMetricsForDpi(WindowsApi.SystemMetricIndex.SM_CYSCREEN, dpi);
        //    if (width == 0 || height == 0)
        //    {
        //        return null;
        //    }

        //    return new Size(width, height);
        //}


        // TODO: To get the coordinates of the portion of the screen that is not obscured by the system taskbar or by application desktop toolbars, call the SystemParametersInfo function with the SPI_GETWORKAREA value instead
        // NOTE: this function is not DPI aware (unless the app is DPI-aware)
        public static Size?GetMainDisplayMonitorFullScreenWindowSizeInPixels()
        {
            // TODO: use alternate GetSystemMetricsForDpi in dpi-aware apps
            // NOTE: GetSystemMetrics returns a scaled DPI value (not the physical number of pixels)
            var width  = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CXFULLSCREEN);
            var height = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CYFULLSCREEN);

            if (width == 0 || height == 0)
            {
                return(null);
            }

            return(new Size(width, height));
        }
        public static List <DisplayAdapterInfo> GetAllDisplayAdapters()
        {
            var result = new List <DisplayAdapterInfo>();

            // get a list of all display adapters
            UInt32 iDisplayAdapter = 0;
            //
            var success = true;

            while (success == true)
            {
                var cDisplayDevice = new WindowsApi.DISPLAY_DEVICEW();
                cDisplayDevice.Init();

                success = WindowsApi.EnumDisplayDevices_DisplayAdapter(IntPtr.Zero, iDisplayAdapter, ref cDisplayDevice, 0);
                if (success == false)
                {
                    break;
                }

                // verify that the device is attached to the desktop
                if ((UInt32)(cDisplayDevice.StateFlags & WindowsApi.DisplayDeviceStateFlags.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) == 0)
                {
                    iDisplayAdapter += 1;
                    continue;
                }
                // verify that the device is not a mirroring psuedodevice
                if ((UInt32)(cDisplayDevice.StateFlags & WindowsApi.DisplayDeviceStateFlags.DISPLAY_DEVICE_MIRRORING_DRIVER) != 0)
                {
                    iDisplayAdapter += 1;
                    continue;
                }

                var deviceNameAsCharArray = cDisplayDevice.DeviceName;
                var deviceNameAsString    = ConvertCharArrayToString(deviceNameAsCharArray);

                var isPrimaryDisplayAdapter = false;
                if ((UInt32)(cDisplayDevice.StateFlags & WindowsApi.DisplayDeviceStateFlags.DISPLAY_DEVICE_PRIMARY_DEVICE) != 0)
                {
                    isPrimaryDisplayAdapter = true;
                }

                var displayAdapterInfo = new DisplayAdapterInfo(deviceNameAsString, isPrimaryDisplayAdapter);
                result.Add(displayAdapterInfo);

                iDisplayAdapter += 1;
            }

            return(result);
        }
        //
        //public static Size? GetMainDisplayMonitorFullScreenWindowSizeInPixels_DpiAware(UInt32 dpi)
        //{
        //    // NOTE: GetSystemMetrics returns a scaled DPI value (not the physical number of pixels)
        //    var width = WindowsApi.GetSystemMetricsForDpi(WindowsApi.SystemMetricIndex.SM_CXFULLSCREEN, dpi);
        //    var height = WindowsApi.GetSystemMetricsForDpi(WindowsApi.SystemMetricIndex.SM_CYFULLSCREEN, dpi);
        //    if (width == 0 || height == 0)
        //    {
        //        return null;
        //    }

        //    return new Size(width, height);
        //}

        // NOTE: this function is not DPI aware (unless the app is DPI-aware)
        public static Rectangle?GetVirtualScreenBoundsInPixels()
        {
            // NOTE: GetSystemMetrics returns a scaled DPI value (not the physical number of pixels)
            var x      = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_XVIRTUALSCREEN);
            var y      = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_YVIRTUALSCREEN);
            var width  = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CXVIRTUALSCREEN);
            var height = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CYVIRTUALSCREEN);

            if (width == 0 || height == 0)
            {
                return(null);
            }

            return(new Rectangle(x, y, width, height));
        }
        // NOTE: this function returns True if the display settings can be set, False otherwise
        // NOTE: this _might_ let us detect if a display change requires a reboot (although we don't yet return a result indicating that reality)
        public static Boolean TestDisplaySettings(String displayAdapterName, DisplaySettings settings)
        {
            var displayAdapterNameAsCharArray = ConvertStringToNullTerminatedCharArray(displayAdapterName);
            var devmode = settings.devmode;
            var result  = WindowsApi.ChangeDisplaySettingsEx(displayAdapterNameAsCharArray, ref devmode, IntPtr.Zero, (UInt32)WindowsApi.ChangeDisplaySettingsFlags.CDS_TEST, IntPtr.Zero);

            switch (result)
            {
            case WindowsApi.DISP_CHANGE_RESULT.DISP_CHANGE_SUCCESSFUL:
                return(true);

            //case WindowsApi.DISP_CHANGE_RESULT.DISP_CHANGE_RESTART:
            default:
                return(false);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// A Window procedure - handles window messages for a window.
        /// Pass this method to HwndSource.AddHook().
        /// </summary>
        /// <param name="hwnd">The window handle.</param>
        /// <param name="msg">The message.</param>
        /// <param name="wParam">Message data.</param>
        /// <param name="lParam">Message data.</param>
        /// <param name="handled">Set to true if the message has been handled</param>
        /// <returns>The message result.</returns>
        public IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch ((WindowsApi.WindowMessages)msg)
            {
            case WindowsApi.WindowMessages.WM_CLIPBOARDUPDATE:
                // The clipboard has been updated.
                this.gotClipboard.Set();
                handled = true;
                break;

            default:
                if (msg == this.shellMessage)
                {
                    // A window has been activated.
                    if (wParam.ToInt32() == WindowsApi.HSHELL_WINDOWACTIVATED ||
                        wParam.ToInt32() == WindowsApi.HSHELL_RUDEAPPACTIVATED)
                    {
                        // The activated window is passed via lParam, but this wasn't accurate
                        // for Modern UI apps.
                        IntPtr window = WindowsApi.GetForegroundWindow();

                        if (this.activeWindow != window)
                        {
                            this.activeWindow = window;

                            // Ignore the application's window
                            WindowsApi.GetWindowThreadProcessId(window, out uint pid);
                            if (pid != this.processId && pid != 0)
                            {
                                this.lastWindow = window;
                            }

                            this.activeWindowChanged.Set();
                        }
                    }
                }

                break;
            }

            return(IntPtr.Zero);
        }
Exemplo n.º 15
0
        public String ReadValue(String key, String section)
        {
            // NOTE: we are using a maximum value length of 255 characters + null; this is somewhat arbitrary, so enlarge maxValueLength if necessary
            var maxValueLength = 256;
            var value          = new String(' ', maxValueLength);

            var actualLength = WindowsApi.GetPrivateProfileString(section, key, "", out value, (UInt32)maxValueLength, _path);

            var lastWin32Error = Marshal.GetLastWin32Error();

            if (lastWin32Error == 0x2) /* file not found*/
            {
                var hresult = Marshal.GetHRForLastWin32Error();
                throw Marshal.GetExceptionForHR(hresult);
            }

            var result = value.Substring(0, (Int32)actualLength);

            return(result);
        }
        // NOTE: this function throws an exception if the settings could not be set successfully
        public static void SetCurrentDisplaySettings(String displayAdapterName, DisplaySettings settings)
        {
            /* OPTIONAL FLAGS:
             * CDS_GLOBAL | CDS_UPDATEREGISTRY  // save the updated resolution for all users
             * CDS_RESET                        // update the settings even if they're the same as the current settings
             * CDS_SET_PRIMARY                  // make this display adapter the primary display adapter
             * CDS_TEST                         // tests if the change would be valid [NOTE: this _might_ let us detect if a display change requires a reboot]
             * CDS_UPDATEREGISTRY               // save the display change in the system registry (for the user, unless also using CDS_GLOBAL)
             * CDS_DISABLE_UNSAFE_MODES         // prohibits us from accidentally using unsafe display modes
             */
            var displayAdapterNameAsCharArray = ConvertStringToNullTerminatedCharArray(displayAdapterName);
            var devmode = settings.devmode;
            var result  = WindowsApi.ChangeDisplaySettingsEx(displayAdapterNameAsCharArray, ref devmode, IntPtr.Zero, 0, IntPtr.Zero);

            switch (result)
            {
            case WindowsApi.DISP_CHANGE_RESULT.DISP_CHANGE_SUCCESSFUL:
                return;

            default:
                throw new Exception("Could not change screen settings; result: " + result);
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Activates a window, does not return until it is activated.
 /// </summary>
 /// <param name="hwnd">The handle of the window to activate.</param>
 private void ActivateWindow(IntPtr hwnd)
 {
     if (hwnd != IntPtr.Zero)
     {
         // Activate the window, if it's not already.
         IntPtr active = WindowsApi.GetForegroundWindow();
         if (active != hwnd)
         {
             // Wait for it to be activated. For unknown reasons, activating the window the first time causes
             // no window to be activated. The second attempt works.
             const int timeout   = 2000;
             int       start     = Environment.TickCount;
             int       timespent = 0;
             do
             {
                 WindowsApi.SetForegroundWindow(hwnd);
                 this.activeWindowChanged.Reset();
                 this.activeWindowChanged.WaitOne(timeout - timespent);
                 timespent = Environment.TickCount - start;
             } while (this.activeWindow != hwnd && timespent <= timeout);
         }
     }
 }
        // NOTE: this function is not DPI aware (unless the app is DPI-aware)
        public static Size?GetMainDisplayMonitorSizeInPixels()
        {
            // implementation option 1:
            // TODO: use alternate GetSystemMetricsForDpi in dpi-aware apps
            // NOTE: GetSystemMetrics returns a scaled DPI value (not the physical number of pixels)
            var width  = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CXSCREEN);
            var height = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CYSCREEN);

            if (width == 0 || height == 0)
            {
                return(null);
            }

            // implementation option 2:
            // TODO: ... width = GetDeviceCaps(hdcPrimaryMonitor, HORZRES);
            // TODO: ... height = GetDeviceCaps(hdcPrimaryMonitor, VERTRES);
            //if (width == 0 || height == 0)
            //{
            //    return null;
            //}

            return(new Size(width, height));
        }
        public static List <DisplaySettings> GetAllDisplaySettingsForDisplayAdapter(String displayAdapterName)
        {
            var result = new List <DisplaySettings>();

            var displayAdapterNameAsCharArray = ConvertStringToNullTerminatedCharArray(displayAdapterName);

            // get the display settings for each graphics mode of this display adapter
            UInt32 iGraphicsMode = 0;

            var success = true;

            while (success == true)
            {
                var devmode = new WindowsApi.DEVMODEW();
                devmode.Init();

                success = WindowsApi.EnumDisplaySettingsEx(displayAdapterNameAsCharArray, iGraphicsMode, ref devmode, 0);
                if (success == false)
                {
                    break;
                }

                var displaySettings = DisplaySettings.CreateNew(devmode);
                if (displaySettings == null)
                {
                    iGraphicsMode += 1;
                    continue;
                }

                result.Add(displaySettings.Value);

                iGraphicsMode += 1;
            }

            return(result);
        }
        public static DisplaySettings?GetCurrentDisplaySettingsForDisplayAdapter(String displayAdapterName)
        {
            var displayAdapterNameAsCharArray = ConvertStringToNullTerminatedCharArray(displayAdapterName);

            var success = true;
            var devmode = new WindowsApi.DEVMODEW();

            devmode.Init();

            success = WindowsApi.EnumDisplaySettingsEx(displayAdapterNameAsCharArray, WindowsApi.ENUM_CURRENT_SETTINGS, ref devmode, 0);
            if (success == false)
            {
                return(null);
            }

            var displaySettings = DisplaySettings.CreateNew(devmode);

            if (displaySettings == null)
            {
                return(null);
            }

            return(displaySettings);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Press or depress a key.
        /// </summary>
        /// <param name="virtualKey">The virtual key code.</param>
        /// <param name="pressed">true to press the key, false to release.</param>
        public static void PressKey(uint virtualKey, bool pressed)
        {
            const uint KEYEVENTF_KEYUP = 0x2;

            WindowsApi.keybd_event((byte)virtualKey, 0, pressed ? 0 : KEYEVENTF_KEYUP, UIntPtr.Zero);
        }
Exemplo n.º 22
0
        // NOTE: historically, virtually all Windows machines will believe that a mouse is present: even if no mouse is plugged in, the presence of a "mouse port" can also register as presence of a mouse
        public static Boolean GetMouseIsPresent()
        {
            var mouseIsPresent = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_MOUSEPRESENT);

            return(mouseIsPresent != 0 ? true : false);
        }
        public static Int32 GetNumberOfVisibleDisplayMonitors()
        {
            var numberOfVisibleDisplayMonitors = WindowsApi.GetSystemMetrics(WindowsApi.SystemMetricIndex.SM_CMONITORS);

            return(numberOfVisibleDisplayMonitors);
        }