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