C#.Net 中有没有办法检查鼠标指针是否可见?(例如在触摸设备上)
还是符号类型呢?(指针,加载圈,隐藏)
看看使用Cursor.Current
表示鼠标光标的 Cursor。如果鼠标光标不可见,则默认值为 null。
所以像
Cursor current = Cursor.Current;
if(current == null)
//the cursor is not visible
else
//the cursor is visible
属性值 类型:System.Windows.Forms.Cursor 表示鼠标光标的 Cursor。如果鼠标光标不可见,则默认值为 null。
所以这段代码应该可以完成这项工作:
If (Cursor.Current == null)
{
// cursor is invisible
}
else
{
// cursor is visible
}
我凭经验发现Cursor.Current == null并不表示光标隐藏状态(Windows 10 Pro、.Net 4.7、Windows.Forms、2020.04.07)。
为了澄清问题,我想检查(未设置)光标隐藏状态,因为这似乎是可靠检测鼠标事件是否由鼠标/触摸板(光标可见)或手指触摸(光标不可见的)。
深入 Win32 调用可以成功检查此状态:
#region Cursor info
public static class CursorExtensions {
[StructLayout(LayoutKind.Sequential)]
struct PointStruct {
public Int32 x;
public Int32 y;
}
[StructLayout(LayoutKind.Sequential)]
struct CursorInfoStruct {
/// <summary> The structure size in bytes that must be set via calling Marshal.SizeOf(typeof(CursorInfoStruct)).</summary>
public Int32 cbSize;
/// <summary> The cursor state: 0 == hidden, 1 == showing, 2 == suppressed (is supposed to be when finger touch is used, but in practice finger touch results in 0, not 2)</summary>
public Int32 flags;
/// <summary> A handle to the cursor. </summary>
public IntPtr hCursor;
/// <summary> The cursor screen coordinates.</summary>
public PointStruct pt;
}
/// <summary> Must initialize cbSize</summary>
[DllImport("user32.dll")]
static extern bool GetCursorInfo(ref CursorInfoStruct pci);
public static bool IsVisible(this Cursor cursor) {
CursorInfoStruct pci = new CursorInfoStruct();
pci.cbSize = Marshal.SizeOf(typeof(CursorInfoStruct));
GetCursorInfo(ref pci);
// const Int32 hidden = 0x00;
const Int32 showing = 0x01;
// const Int32 suppressed = 0x02;
bool isVisible = ((pci.flags & showing) != 0);
return isVisible;
}
}
#endregion Cursor info
客户端代码现在非常方便:
bool isTouch = !Cursor.Current.IsVisible();
您可以使用System.Windows.Forms.Cursor
类来获取信息;
使用Cursor.Current
属性!
if (Cursor.Current == null)
{
//
}
如果您谈论的是 WPF 变体,那么框架元素的 Cursor 属性应该是None
如果它不可见。