2

How do I use Binary-AND to check if a particular bit is set for an IntPtr object?

I'm calling GetWindowLongPtr32() API to get window style for a window. This function happens to return an IntPtr. I have defined all the flag constants in my program. Now suppose if I want to check whether a particular flag (say WS_VISIBLE) is set, I need to Binary-AND it with my constant, but my constant is of int type, so I cannot do that directly. Try to call ToInt32() and ToInt64() both result in (ArgumentOutOfRangeException) exception. What's my way out?

dotNET
  • 33,414
  • 24
  • 162
  • 251
  • What is the exact exception you get from ToInt32? – LightStriker Apr 16 '13 at 12:20
  • Have you tried [`GetWindowLongPtr`](http://www.pinvoke.net/default.aspx/user32/GetWindowLongPtr.html)? – Dustin Kingen Apr 16 '13 at 12:21
  • @Romoku: I read somewhere that `GetWindowLongPtr` is a macro that internally calls `GetWindowLongPtr32()` or `GetWindowLongPtr64()` depending upon the platform. – dotNET Apr 16 '13 at 12:23
  • @LightStriker: ArgumentOutOfRangeException. Internal message is "Enum value was out of legal range." – dotNET Apr 16 '13 at 12:25
  • Take a look at this question. http://stackoverflow.com/questions/1271220/getwindowlongint-hwnd-gwl-style-return-weird-numbers-in-c-sharp – Dustin Kingen Apr 16 '13 at 12:36

2 Answers2

2

Just convert IntPtr to an int (it has a conversion operator) and use logical bit operators to test bits.

const int WS_VISIBLE = 0x10000000;
int n = (int)myIntPtr;
if((n & WS_VISIBLE) == WS_VISIBLE) 
    DoSomethingWhenVisible()`
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
-1

How do I pinvoke to GetWindowLongPtr and SetWindowLongPtr on 32-bit platforms?

public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex)
{
    if (IntPtr.Size == 4)
    {
        return GetWindowLong32(hWnd, nIndex);
    }
    return GetWindowLongPtr64(hWnd, nIndex);
}


[DllImport("user32.dll", EntryPoint="GetWindowLong", CharSet=CharSet.Auto)]
private static extern IntPtr GetWindowLong32(HandleRef hWnd, int nIndex);

[DllImport("user32.dll", EntryPoint="GetWindowLongPtr", CharSet=CharSet.Auto)]
private static extern IntPtr GetWindowLongPtr64(HandleRef hWnd, int nIndex);

GetWindowLong(int hWnd, GWL_STYLE) return weird numbers in c#

You can implicit cast IntPtr to int to get the result.

var result = (int)GetWindowLong(theprocess.MainWindowHandle, GWL_STYLE);
bool isVisible = ((result & WS_VISIBLE) != 0);
Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • WS_VISIBLE (as well as all the WS_ values--otherwise you couldn't write a 32-bit Windows application) is a 32-bit value. It doesn't matter if you use only the bottom 32 bits of the windows long because you're just going to mask off everything in the top 32-bits anyway. – Peter Ritchie Apr 16 '13 at 12:42