gpt4 book ai didi

c# - 将 Ctrl+C 发送到上一个事件窗口

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:16 25 4
gpt4 key购买 nike

我正在尝试编写一个位于系统托盘中的小型应用程序。我已经注册了一个热键。当触发热键并激活应用程序时,我想将 Ctrl+C 发送到最后一个事件窗口,这样我就可以将突出显示的文本放入剪贴板。

这是我到目前为止得到的:

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

但我无法让 SendKeys 工作。在大多数应用程序中,什么都没有发生,这意味着 ctrl-c 不会被触发。在 Ms Word 中,当执行 SendWait 时,我的文档中插入了一个版权符号 (c)。

更新:

我试过使用 WM_COPY 和 SendMessage:

private static void OnHotKeyFired()
{
IntPtr handle = GetPreviousWindow();
SendMessage(handle, WM_COPY, IntPtr.Zero, IntPtr.Zero);
_viewModel.Input = Clipboard.GetText();
...

它在 Word 中有效,但在 Excel、记事本、Visual Studio 中无效

最佳答案

    SendKeys.SendWait("^(c)");

那不发送 Ctrl+C,括号也被发送。您的意思可能是 "^{c}",花括号而不是圆括号。否则,由于 Word 插入版权符号的原因,它会自动将 (c) 更正为 ©。修复:

    SendKeys.SendWait("^c");

如果仍然有问题,您可能会遇到问题,然后阅读有关 SendKeys 的 MSDN 文章。它建议使用 .config 文件,以便使用不同的方式来注入(inject)击键。 SendInput() 在更高版本的 Windows 上比日志 Hook 更好用。

关于c# - 将 Ctrl+C 发送到上一个事件窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28969057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com