0

I know that when doing drag-drop I can do something like

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

to make the cursor have a plus image meaning copy. I am just wondering if I can do this when I am not doing drag-drop (for example when the user clicks a specific place the cursor changes to this style until the user clicks somewhere else). I tried using Cursor = Cursors.<style> but it does not contain this. Any ideas ?

4

1 回答 1

2

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

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

    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);
于 2013-05-10T11:13:23.250 回答