【问题标题】:Extract Text from External Application's Textbox(Unicode) into C# Application, using user32.dll使用 user32.dll 从外部应用程序的文本框(Unicode)中提取文本到 C# 应用程序中
【发布时间】:2013-08-15 20:56:28
【问题描述】:

我在 C# 中开发了一个应用程序,它从外部应用程序的文本框中提取文本,我正在使用 user32.dll,该应用程序工作正常,但我的问题是 - 外部应用程序的文本框包含 unicode 格式的文本,所以每当我提取我的应用程序中的文本显示“??????”文本。我尝试设置 charset.unicode ,并且还使用 RichTextBox 在我的应用程序中显示文本。 请让我知道如何从外部应用程序中提取 unicode 文本。

这是我正在使用的代码

 private void button1_Click(object sender, EventArgs e)
    { IntPtr MytestHandle = new IntPtr(0x00060342);

        HandleRef hrefHWndTarget = new HandleRef(null, MytestHandle);

     // encode text into 
        richTextBox1.Text = ModApi.GetText(hrefHWndTarget.Handle);
     }

公共静态类 ModApi {
[DllImport("user32.dll", EntryPoint = "SendMessageTimeout", SetLastError = true, CharSet = CharSet.Unicode)] public static extern uint SendMessageTimeoutText(IntPtr hWnd, int Msg, int countOfChars, StringBuilder text, uint flags, uint uTImeoutj, uint result);

        public static string GetText(IntPtr hwnd)
        {
            var text = new StringBuilder(1024);

            if (SendMessageTimeoutText(hwnd, 0xd, 1024, text, 0x2, 1000, 0) != 0)
            {
                return text.ToString();
            }

            MessageBox.Show(text.ToString());
            return "";
        }
    }

【问题讨论】:

  • 显然 Richedit 控件正在一个非 Unicode 启用的程序中使用。效果很好,显示 Unicode 字形没有问题,因为 RTF 只使用 ASCII 字符。您需要获取 RTF 而不是显示的文本。这需要 EM_STREAMOUT 消息。问题是,您只能从在进程内部运行的代码中使用该消息。你不能注入 C# 代码。

标签: c# .net user-interface


【解决方案1】:

您对 WN_GETTEXT 的使用不正确,请阅读文档:http://msdn.microsoft.com/en-us/library/windows/desktop/ms632627%28v=vs.85%29.aspx

wParam

The maximum number of characters to be copied, including the terminating null character. 

或使用正确的函数:http://www.pinvoke.net/default.aspx/user32/GetWindowText.html

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);

public static string GetWindowTextRaw(IntPtr hwnd)
{
    // Allocate correct string length first
    int length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
    StringBuilder sb = new StringBuilder(length + 1);
    SendMessage(hwnd, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
    return sb.ToString();
}

使其适应 SendMessageTimeOut

【讨论】:

  • int 长度 = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);此行显示错误。
  • 我能够从外部应用程序获取文本,但无法获取 unicode,而是显示“????”。
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 2010-09-06
  • 2014-01-25
  • 2012-12-14
  • 2012-01-12
  • 1970-01-01
  • 2014-03-21
  • 2011-11-17
相关资源
最近更新 更多