dahall / Vanara

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
MIT License
1.75k stars 190 forks source link

User32.GetWindowLongAuto throws an exception if result is 0 #442

Closed vlad2048 closed 3 months ago

vlad2048 commented 4 months ago

Describe the bug and how to reproduce

0 is a valid return value for GetWindowLong & GetWindowLongPtr. So it cannot be used alone to detect an error.

For example querying the extended styles (WindowStylesEx) of a window can return 0 as a valid value.

What code is involved

// PInvoke\User32\WinUser.Gdi.cs
public static IntPtr GetWindowLongAuto(HWND hWnd, WindowLongFlags nIndex)

Expected behavior Instead of just checking the return value against 0, we should:

Screenshots n/a

dahall commented 3 months ago

I have updated the function as follows:

public static IntPtr GetWindowLongAuto(HWND hWnd, WindowLongFlags nIndex)
{
    SetLastErrorEx(0, 0);
    IntPtr ret = IntPtr.Size == 4 ? GetWindowLong(hWnd, nIndex) : GetWindowLongPtr(hWnd, nIndex);
    if (ret == IntPtr.Zero)
        Win32Error.GetLastError().ThrowIfFailed();
    return ret;
}