I'm trying to write a small application that's sits in the system tray. I've registered a hotkey. When the hotkey is fired and the application is activated I want to send Ctrl+C to the last active window so I can get the highlighted text into the clipboard.
This is what I got so far:
//http://stackoverflow.com/questions/9468476/switch-to-last-active-application-like-alt-tab
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr GetLastActivePopup(IntPtr hWnd);
[DllImport("user32.dll", ExactSpelling = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
const uint GA_PARENT = 1;
const uint GA_ROOT = 2;
const uint GA_ROOTOWNER = 3;
public static IntPtr GetPreviousWindow()
{
IntPtr activeAppWindow = GetForegroundWindow();
if (activeAppWindow == IntPtr.Zero)
return IntPtr.Zero;
IntPtr prevAppWindow = GetLastActivePopup(activeAppWindow);
return IsWindowVisible(prevAppWindow) ? prevAppWindow : IntPtr.Zero;
}
public static void FocusToPreviousWindow()
{
IntPtr prevWindow = GetPreviousWindow();
if (prevWindow != IntPtr.Zero)
SetForegroundWindow(prevWindow);
}
...
private static void OnHotKeyFired()
{
FocusToPreviousWindow();
SendKeys.SendWait("^(c)");
_viewModel.Input = Clipboard.GetText();
new UIWindow(_viewModel).ShowDialog();
}
But I can't get the SendKeys to work. In most apps nothing happpens, meaning ctrl-c is not fired. In Ms Word a copyright sign (c) is inserted in my document when SendWait is executed.
UPDATE:
I've tried with WM_COPY and SendMessage:
private static void OnHotKeyFired()
{
IntPtr handle = GetPreviousWindow();
SendMessage(handle, WM_COPY, IntPtr.Zero, IntPtr.Zero);
_viewModel.Input = Clipboard.GetText();
...
And it works in Word but not in Excel, Notepad, Visual Studio