gpt4 book ai didi

c# - 我如何在 C# 中模拟 CTRL+C

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

我有以下代码,在记事本中可以正常工作,但在 WORD 中却不行!!

 [DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();

[DllImport("user32.dll")]
public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

[DllImport("user32.dll")]
public static extern IntPtr GetFocus();

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);

// second overload of SendMessage
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);

[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

public const uint WM_GETTEXT = 0x0D;
public const uint WM_GETTEXTLENGTH = 0x0E;
public const uint EM_GETSEL = 0xB0;

IntPtr hWnd = WinUser.GetForegroundWindow();
uint processId;
uint activeThreadId = WinUser.GetWindowThreadProcessId(hWnd, out processId);
uint currentThreadId = WinUser.GetCurrentThreadId();

WinUser.AttachThreadInput(activeThreadId, currentThreadId, true);
IntPtr focusedHandle = WinUser.GetFocus();
WinUser.AttachThreadInput(activeThreadId, currentThreadId, false);

int len = WinUser.SendMessage(focusedHandle, WinUser.WM_GETTEXTLENGTH, 0, null);
StringBuilder sb = new StringBuilder(len);
int numChars = WinUser.SendMessage(focusedHandle, WinUser.WM_GETTEXT, len + 1, sb);

int start, next;
string selectedText = "";
WinUser.SendMessage(focusedHandle, WinUser.EM_GETSEL, out start, out next);
try
{
selectedText = sb.ToString().Substring(start, next - start);
}

不幸的是,当在 WORD 或任何“richtextbox”中选择文本时,上述返回“{Microsoft Word Document}”。CTRL+C是怎么做到的?

注意:这在记事本或任何简单的文本编辑器中都可以正常工作。

最佳答案

关于c# - 我如何在 C# 中模拟 CTRL+C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1859061/

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