gpt4 book ai didi

c# - Cursor.Current 与 this.Cursor

转载 作者:IT王子 更新时间:2023-10-29 03:47:50 30 4
gpt4 key购买 nike

.Net 中的 Cursor.Currentthis.Cursor(this 是 WinForm)之间有区别吗?我一直使用 this.Cursor 并且运气很好,但我最近开始使用 CodeRush 并将一些代码嵌入到“Wait Cursor” block 中,而 CodeRush 使用了 Cursor.Current 属性。我在 Internet 上和工作中看到其他程序员对 Cursor.Current 属性有一些问题。这让我想知道两者是否有区别。提前致谢。

我做了一个小测试。我有两个winform。我单击 form1 上的一个按钮,将 Cursor.Current 属性设置为 Cursors.WaitCursor,然后显示 form2。两种形式的光标都不会改变。它仍然是 Cursors.Default(指针)光标。

如果我在 form1 上的按钮单击事件中将 this.Cursor 设置为 Cursors.WaitCursor 并显示 form2,则等待光标仅显示在 form1 上,默认光标为在预期的 form2 上。所以,我仍然不知道 Cursor.Current 的作用。

最佳答案

Windows 向包含鼠标光标的窗口发送 WM_SETCURSOR 消息,使其有机会更改光标形状。像 TextBox 这样的控件利用了这一点,将光标更改为 I-bar。 Control.Cursor 属性决定了将使用什么形状。

Cursor.Current 属性直接更改形状,无需等待 WM_SETCURSOR 响应。在大多数情况下,这种形状不太可能长期存在。一旦用户移动鼠标,WM_SETCURSOR 就会将其变回 Control.Cursor。

.NET 2.0 中添加了 UseWaitCursor 属性,以便更轻松地显示沙漏。不幸的是,它不是很好用。它需要 WM_SETCURSOR 消息来更改形状,当您将属性设置为 true 然后执行需要一段时间的操作时,这不会发生。例如试试这个代码:

private void button1_Click(object sender, EventArgs e) {
this.UseWaitCursor = true;
System.Threading.Thread.Sleep(3000);
this.UseWaitCursor = false;
}

光标永远不会改变。要使其成形,您还需要使用 Cursor.Current。这里有一个小助手类可以使它变得简单:

using System;
using System.Windows.Forms;

public class HourGlass : IDisposable {
public HourGlass() {
Enabled = true;
}
public void Dispose() {
Enabled = false;
}
public static bool Enabled {
get { return Application.UseWaitCursor; }
set {
if (value == Application.UseWaitCursor) return;
Application.UseWaitCursor = value;
Form f = Form.ActiveForm;
if (f != null && f.Handle != IntPtr.Zero) // Send WM_SETCURSOR
SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1);
}
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

然后像这样使用它:

private void button1_Click(object sender, EventArgs e) {
using (new HourGlass()) {
System.Threading.Thread.Sleep(3000);
}
}

关于c# - Cursor.Current 与 this.Cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/302663/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com