0

Not GetWindowText hangs on Windows 10

A C# WinForms application hangs at a call to GetWindowTextLength inside EnumWindows.

The target window of GetWindowTextLength is in the same process of the caller since the parameter onlyCurrentProcess in the bellow code is true when hang.

Clue: The hang seems to only happen when the monitor is turned on or off which may trigger some window change on the desktop. But since even the target window is not responding or doesn't exist, GetWindowTextLength will still work, then how can this hang happen? The question is asking for some starting point about when can GetWindowText(Length) hang.

    public static string GetWindowText(IntPtr hWnd)
    {
        //get hang here
        int size = GetWindowTextLength(hWnd);
        ......
    }

The above is the minimal (not easy to reproduce even in my environment, but it has happened for serveral times, all when the monitor is turned on/off but not each time the monitor is turned on/off) example.

Updated:

GetWindowText will also hang at that point.

Updated:

It is highly possible Why does GetWindowText hang with a "closed" handle but not with a random one is the reason, i.e. some system window get closed when the monitor is turned on/off which is enumerated before the event and used after the event.

jw_
  • 1,663
  • 18
  • 32
  • 2
    You've not reduced this down to an [mcve]. I'd suspect the issue is that you're calling this from (and blocking) the UI thread which therefore isn't available to service the WM_GETTEXTLENGTH message that the function sends. – Damien_The_Unbeliever Nov 30 '20 at 08:27
  • @Damien_The_Unbeliever Calling them from the UI thread is the standard use case. It will work even for a non-responding window will work. It just should not hang. – jw_ Nov 30 '20 at 08:34
  • In another thread, someone wrote: "GetWindowText will hang (IE: never return) if passed a handle to a recently closed application". Are other threads running that are closing windows? – Loathing Nov 30 '20 at 09:04
  • @Loathing Will it only hang on "recently closed"? What is that thread? – jw_ Nov 30 '20 at 09:07
  • 2
    https://stackoverflow.com/questions/5440629/why-does-getwindowtext-hang-with-a-closed-handle-but-not-with-a-random-one – Loathing Nov 30 '20 at 09:10
  • @Loathing That should be the reason if that is true, though it will never be sure. – jw_ Nov 30 '20 at 09:14

1 Answers1

-1

Could be the Charset.Unicode causing the issue. Have you tried just getting the title itself?

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static String GetWindowText(IntPtr hWnd) {
    StringBuilder sb = new StringBuilder(256);
    GetWindowText(hWnd, sb, sb.Capacity);
    return sb.ToString();
}
Loathing
  • 5,109
  • 3
  • 24
  • 35