6

I am using this: to get window's title by its handle:

[DllImport("user32.dll")] private static extern int GetWindowText(int hWnd, StringBuilder title, int size);

StringBuilder title = new StringBuilder(256);
GetWindowText(hWnd, title, 256);

If the title has hebrew chars, it replaces them by question marks.
I guess the problem is related to econding or something... how can I solve it?

Ron
  • 3,975
  • 17
  • 80
  • 130

2 Answers2

9

Your question contains a little error, that might not occurs very often. You assume, that the title has a max length of 256 characters, which might be enough for most cases. But as this post shows, the length could be at 100K characters, maybe more. So I would use another helper function: GetWindowTextLength

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);

public static string GetWindowTitle(IntPtr hWnd)
{
    var length = GetWindowTextLength(hWnd) + 1;
    var title = new StringBuilder(length);
    GetWindowText(hWnd, title, length);
    return title.ToString();
}
Julio Nobre
  • 4,196
  • 3
  • 46
  • 49
0xBADF00D
  • 980
  • 1
  • 12
  • 25
  • 6
    For me length always equals (real length -1). Not sure why, but simple `var length = GetWindowTextLength(hwnd) + 1;` fixes my problem. – Alex Wyler May 25 '20 at 17:12
  • @alexWyler I stumbled upon the same issue but forget to update my answer. I assume GetWindowTitle returns the length without the terminator \0 that is used in C and C++ to mark the end of the string. But its only a guess – 0xBADF00D Mar 12 '21 at 07:36
7

Use this:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowText(int hWnd, StringBuilder title, int size);
Louis Go
  • 2,213
  • 2
  • 16
  • 29
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68