简体   繁体   中英

C# Event-Handling

I am working on a C# piano. I have already built the music keyboard and the staff. Everytime a user presses a key, it is displayed on the staff in its relevant position.

The music note displayed on the staff is stored in an array of pictureboxes, as shown below.

public void addPictureBox(int x, int y, Image image)
{
    picBox[cnt] = new PictureBox();

    picBox[cnt].Image = image;
    picBox[cnt].Location = new Point(x, y);
    picBox[cnt].BackColor = Color.Transparent;

    panel3.Controls.Add(picBox[cnt]);
    picBox[cnt].BringToFront();
    picBox[cnt].MouseDown += new MouseEventHandler(Pic_MouseDown);
    picBox[cnt].MouseUp += new MouseEventHandler(Pic_MouseUp);

    cnt++;
}

The Pic_MouseDown and Pic_MouseUp events allow the user to play the note by clicking on it from the staff.

What I want to do now is to create an event on picBox[cnt] for dragging. However, picBox[cnt].MouseDown and picBox[cnt].MouseUp have already been registered to Pic_MouseDown and Pic_MouseUp event handlers.

How can I do an event to handle dragging since MouseDown and MouseUp have already been registered to other event handlers?

Thanks :)

The great thing about event handlers is that you can have as many attached handlers as you want. The += ( operator overload ) means you are attaching a new event handler to the existing handlers. You can add as many event handlers as you desire.

Event Handler Overview

如果创建一个isDragging布尔实例字段,并在鼠标按下时将其设置为true,在鼠标按下时将其设置为false,则可以使用鼠标移动事件来检测是否应移动对象。

You'll need to use a combination of MouseDown, MouseMove and MouseUp events. In MouseDown, you do little more than set a flag to indicate that the mouse was pressed, and record where it was pressed. In MouseMove, you check to see if the button is still down and the cursor has moved further than SystemInformation.DragSize , which indicates that the user is dragging rather than clicking, and start the drag operation if needed. In MouseUp, you either complete the drag or perform the click action.

I believe the conventional wisdom for Drag-n-drop is

  • Call DoDragDrop in the (source control's) MouseDown handler
  • set AllowDrop = true in the targe control's AllowDrop property
  • There's a whole series of drag events to fine tune behavior
  • One does not seem to have to worry about any latent MouseUp or MouseClick events. I'm assuming this is because the physical actions of button press and release are done over different controls and/or the mouse physically moved "far enough".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM