如何使用二进制和检查是否为IntPtr对象设置了特定的位?
我正在调用GetWindowLongPtr32()接口来获取窗口的窗口样式。此函数恰好返回一个IntPtr。我已经在我的程序中定义了所有标志常量。现在假设如果我想检查是否设置了一个特定的标志(比如WS_VISIBLE),我需要对其进行二进制操作-并将其与我的常量一起使用,但我的常量是int类型的,所以我不能直接执行此操作。尝试调用ToInt32()和ToInt64()都会导致(ArgumentOutOfRangeException)异常。我的出路是什么?
发布于 2013-04-16 20:27:42
只需将IntPtr转换为int (它有一个转换运算符),并使用逻辑位运算符来测试位。
const int WS_VISIBLE = 0x10000000;
int n = (int)myIntPtr;
if((n & WS_VISIBLE) == WS_VISIBLE)
DoSomethingWhenVisible()`发布于 2013-04-16 20:39:12
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#
您可以将IntPtr隐式强制转换为int以获得结果。
var result = (int)GetWindowLong(theprocess.MainWindowHandle, GWL_STYLE);
bool isVisible = ((result & WS_VISIBLE) != 0);https://stackoverflow.com/questions/16036783
复制相似问题