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