GetFocus - Win32api的帮助

时间:2011-07-01 13:18:23

标签: c# windows winapi

我正在尝试从用户计算机上的打开表单中获取所选文本。目前我尝试使用GetFocus定义为

    '[DllImport("user32.dll")]
    static extern int GetFocus();'

在api中它说 - Retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue.这解释了为什么我的应用程序可以从我的应用程序的一部分窗口中获取所选文本,但不能从外部获取,例如pdf。

我可以使用哪种替代win32方法来满足此目的?

感谢。

编辑:这是目前的尝试

[的DllImport( “USER32.DLL”)]     static extern int GetFocus();

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

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

[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);

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

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);


// second overload of SendMessage

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

const int WM_SETTEXT = 12;
const int WM_GETTEXT = 13;

private static string PerformCopy()
{
    try
    {
        //Wait 5 seconds to give us a chance to give focus to some edit window,
        //notepad for example
        System.Threading.Thread.Sleep(1000);
        StringBuilder builder = new StringBuilder(500);

        int foregroundWindowHandle = GetForegroundWindow();
        uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
        uint currentThreadId = GetCurrentThreadId();

        //AttachTrheadInput is needed so we can get the handle of a focused window in another app
        AttachThreadInput(remoteThreadId, currentThreadId, true);
        //Get the handle of a focused window


        int focused = GetFocus();




        //Now detach since we got the focused handle
        AttachThreadInput(remoteThreadId, currentThreadId, false);

        //Get the text from the active window into the stringbuilder
        SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);

        return builder.ToString();
    }
    catch (System.Exception oException)
    {
        throw oException;
    }
}

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我认为您没有太多机会成功使用您当前的方法。我很确定没有单一的通用API来获取当前选择。我相信这是因为每个应用程序都可以以自己的方式实现文本选择。

作为替代解决方案,您应该考虑使用clipboard listener。收听剪贴板内容的更改,无论何时添加文本,您都可以将其从剪贴板中取出并将其放入应用程序窗口。

答案 2 :(得分:0)

我认为这是UI Automation(API屏幕阅读器使用)的工作。这是一个得到selected text in C#的帖子。