1

When I try to call a function from User32.dll in C#, SetWindowLong, nothing happens. I know why, but I don't know how to "repair" this. Here's a piece of code.

[DllImport("user32.dll")]
public static extern long GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
public static extern long SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
const int WS_EX_TOPMOST = 0x00000008;
const int GWL_EXSTYLE = -20;
public static bool IsWindowTopMost(int id)
{
    return (GetWindowLong(GetHWNDById(id), GWL_EXSTYLE) & WS_EX_TOPMOST) == WS_EX_TOPMOST;
}
public static void SetAlwaysOnTop(int id)
{
    IntPtr hWnd = GetHWNDById(id);
    long actuallyStyle = GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_TOPMOST;
    SetWindowLong(hWnd, GWL_EXSTYLE, (int)actuallyStyle));
}

IsWindowTopMost works fine, but SetAlwaysOnTop does not. After a quick examination of the code, I found something interesting. Variable "actuallyStyle" after GetWindowLong is equal to 4295295232, after OR operation 4295295240. Here is the problem, function SetWindowLong accepts as dwNewLong a Integer. When I change int with long in the definition of SetWindowLong, pinvoke throws an error, because "unmatched function and target function".

How does it get around?

1

1 Answer 1

3

The correct way to put a window always on top is to use the SetWindowPos function. Problem is most likely that SetWindowLong just sets a variable, but SetWindowPos actually notifies the window manager to do the needed redrawing, so use that instead.

Now about the question title, both SetWindowLong and GetWindowLong must be declared as int, not as long.
This follows 2 reasons are for that. First, the differences between C and C#. The entire Windows API documentation is defined in C terms, where long means 32 bits signed integer, but C# threats long as a 64 bits signed integer, hence giving the error you're getting. Functions using 64 bits are declared in the API documentation as long long.
Another reason for that difference is historical. Both functions where created in the 16 bits era of Windows, where int was 16 bits and long 32 bits. The int type was expanded latter on, but long remained as it was. The name wasn't changed to keep compatibility.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.