5

c# を使用して、任意のウィンドウから強調表示/選択されたテキストを読み取る方法。

私は2つのアプローチを試みました。

  1. ユーザーが何かを選択するたびに「^c」を送信します。しかし、この場合、私のクリップボードは大量の不要なデータであふれています。時々、パスワードもコピーしました。

そのため、アプローチを2番目の方法であるメッセージ送信方法に切り替えました。

このサンプルコードを参照してください

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

このコードはメモ帳で正常に動作します。しかし、Mozilla firefox や Visual Studio IDE などの別のアプリケーションからキャプチャしようとすると、テキストが返されません。

誰が私を助けてくれますか? まず第一に、私は正しいアプローチを選択しましたか?

4

1 に答える 1

3

これは、Firefox と Visual Studio の両方が組み込みの Win32 コントロールを使用してテキストを表示/編集しないためです。

一般に、「任意の」選択されたテキストの値を取得することはできません。これは、プログラムが Win32 コントロールの独自のバージョンを適切と思われる方法で再実装できるため、プログラムがそれを期待できないためです。それらすべてで動作します。

ただし、ほとんどのサードパーティ コントロールと対話できるUI オートメーションAPI を使用できます(少なくとも、Visual Studio や Firefox などのすべての優れたコントロールは、UI オートメーション API で動作する可能性があります。アクセシビリティの要件)

于 2010-05-04T07:41:49.600 に答える