更改光标形状以具有复制光标形状

时间:2013-05-10 07:52:00

标签: c# image cursor

我知道在进行拖放操作时,我可以执行类似

的操作
private void Form_DragOver(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Copy;
}

使光标具有加号图像意味着复制。我只是想知道当我没有进行拖放操作时是否可以执行此操作(例如,当用户单击特定位置时,光标将更改为此样式,直到用户单击其他位置为止)。我尝试使用Cursor = Cursors.<style>,但它不包含此内容。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

除非您想显示等待光标,否则这很难做到。一个特殊情况,由Application.UseWaitCursor属性处理。问题是每个控件本身都会影响光标的形状,由Cursor属性选择。例如,TextBox将坚持将形状更改为I-bar。

只需要在两次点击之间执行此操作,您就会领先一步。在这种情况下可以使用一些技巧,您可以在单击按钮时捕获鼠标,以便光标形状完全由按钮控制。当用户再次单击鼠标时需要进行黑客攻击,该单击将转到相同的按钮,而不是单击任何控件。这需要通过合成另一次点击来修复。此示例代码完成了此操作:

    bool CustomCursorShown;

    private void button1_MouseUp(object sender, MouseEventArgs e) {
        if (button1.DisplayRectangle.Contains(e.Location)) {
            this.BeginInvoke(new Action(() => {
                CustomCursorShown = true;
                button1.Cursor = Cursors.Help;   // Change this to the cursor you want
                button1.Capture = true;
            }));
        }
    }

    private void button1_MouseDown(object sender, MouseEventArgs e) {
        if (CustomCursorShown) {
            var pos = this.PointToClient(button1.PointToScreen(e.Location));
            var ctl = this.GetChildAtPoint(pos);
            if (ctl != null && e.Button == MouseButtons.Left) {
                // You may want to alter this if a special action is required
                // I'm just synthesizing a MouseDown event here...
                pos = ctl.PointToClient(button1.PointToScreen(e.Location));
                var lp = new IntPtr(pos.X + pos.Y << 16);
                // NOTE: taking a shortcut on wparam here...
                PostMessage(ctl.Handle, 0x201, (IntPtr)1, lp);
            }                 
        }
        button1.Capture = false;
    }

    private void button1_MouseCaptureChanged(object sender, EventArgs e) {
        if (!button1.Capture) {
            CustomCursorShown = false;
            button1.Cursor = Cursors.Default;
        }
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private extern static IntPtr PostMessage(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp);