0
votes

I have developed an Application in C# which extract text from external application's textbox , I am using user32.dll, The application is working fine but my problem is this - The external application's textbox contains text in unicode format, so whenever I extract text in my application it shows "??????" text. I have tried setting charset.unicode , and also used RichTextBox to show text in my application. Please let me know how to exract unicode text from external application.

Here is code I am using

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

public static class 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 "";
        }
    }
1
Clearly the Richedit control is being used in a non-Unicode enabled program. Which works fine, it has no trouble displaying Unicode glyphs since RTF only uses ASCII characters. You'll need to obtain the RTF instead of the displayed text. That requires the EM_STREAMOUT message. Problem is, you can only use that message from code that runs inside of the process. You cannot inject C# code.Hans Passant

1 Answers

0
votes

your use of WN_GETTEXT is not correct read the doc : 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. 

or use a correct function : 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();
}

adapt it to SendMessageTimeOut