Why GetWindowText hangs with a "closed" handle, but not with a random one

Using the following code

[DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount); public static String GetWindowText(IntPtr hWnd) { StringBuilder title = new StringBuilder(MAX_TITLE_LENGTH); int titleLength = WinAPI.GetWindowText(hWnd, title, title.Capacity + 1); title.Length = titleLength; return title.ToString(); } 

GetWindowText will freeze (IE: never return) if you pass the handle to a recently closed application. (Which is strange for me, because I would have thought that it would just return with a zero value)

A transition to a random descriptor, such as new IntPtr(123456) , succeeds and returns without a value.

Can anyone explain this behavior?

+4
source share
2 answers

Read the GetWindowText undercovers description here: The Secret Life of GetWindowText .

I don’t think that you will ever get the best :-) If you really want to be 100% sure that you will not hang it, you need to do this in another thread that you can control yourself (i.e. Kill, if you need)

+1
source

It is impossible to answer this question in any meaningful way. The Win32 interface makes no guarantee what happens when you pass invalid window handles to routines. This is mistake. Please refrain.

Having said all this, passing title.Capacity + 1 to GetWindowText is a mistake even with a valid window handle.

0
source

Source: https://habr.com/ru/post/1345310/


All Articles