2013-04-16 144 views
1

如何使用Binary-AND检查是否为IntPtr对象设置了特定位?我打电话给GetWindowLongPtr32() API来获取窗口的窗口样式。这个函数恰好返回一个IntPtr。我已经在我的程序中定义了所有的标志常量。现在假设我想检查是否设置了一个特定的标志(比如说WS_VISIBLE),我需要二进制 - 它与我的常量,但我的常数是int类型,所以我不能直接做到这一点。尝试拨打ToInt32()ToInt64()都会导致(ArgumentOutOfRangeException)异常。我的出路是什么?位屏蔽IntPtr

+0

从ToInt32得到的确切例外是什么? – LightStriker

+0

你有没有试过['GetWindowLongPtr'](http://www.pinvoke.net/default.aspx/user32/GetWindowLongPtr.html)? – Romoku

+0

@Romoku:我在某处读取GetWindowLongPtr是一个根据平台调用GetWindowLongPtr32()或GetWindowLongPtr64()的宏。 – dotNET

回答

1

只需将IntPtr转换为int(它有一个转换运算符)并使用逻辑位运算符来测试位。

const int WS_VISIBLE = 0x10000000; 
int n = (int)myIntPtr; 
if((n & WS_VISIBLE) == WS_VISIBLE) 
    DoSomethingWhenVisible()` 
+0

好吧,为什么downvote? OP究竟是在简单而简洁地问什么? –

+0

这显然对我来说工作得很好。谢谢彼得。 – dotNET

-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#

您可以隐式转换IntPtrint得到的结果。

var result = (int)GetWindowLong(theprocess.MainWindowHandle, GWL_STYLE); 
bool isVisible = ((result & WS_VISIBLE) != 0); 
+0

WS_VISIBLE(以及所有WS_值 - 否则无法写入32位Windows应用程序)是一个32位值。无论如何,只使用窗口的底部32位长,因为您只是要屏蔽顶部32位的所有内容。 –