我需要一个.NET Framework标准事件中不存在的事件。例如,鼠标左键移动时鼠标移动。
我还需要改变一些行为。例如,我有一些按钮,我想在鼠标左键按下时更改光标所在的每个按钮的背景图像,但是当我单击一个按钮并按住鼠标左键时,我移动鼠标时其他按钮不会引发任何事件。
我该怎么办?如何创建新活动?我该如何改变行为?
感谢任何帮助。
答案 0 :(得分:6)
你的问题是当一个按钮上发生MouseDown事件时,该按钮“捕获”鼠标并且在释放按钮之前不会释放它,这意味着其他按钮不会接收到MouseMove事件。 / p>
有一些代码from here可能有所帮助:
// Assuming all buttons subscribe to this event:
private void buttons_MouseMove (object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Control control = (Control) sender;
if (control.Capture)
{
control.Capture = false;
}
if (control.ClientRectangle.Contains (e.Location))
{
Control.BackgroundImage = ...;
}
}
}
答案 1 :(得分:3)
MouseMove-Event有一个名为'Button'的属性,告诉你按下了哪个按钮。所以你要做的就是这样:
void panel1_MouseMove(Object sender, System::Windows::Forms::MouseEventArgs e) {
if(e.Button = MouseButtons.Left){
//Do what you want when mouse_move with left button pressed
}
}
以上代码未经过测试,我没有查找属性的正确拼写等,只需在IntelliSense / MSDN中尝试一下。
您可以在MSDN中找到更多信息: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousemove%28v=vs.71%29.aspx
对于第二个问题,只需尝试找到拟合事件或覆盖WindowProc-Event-Function,您就可以收听WindowMessages并获取所需内容 - 更多信息在http://msdn.microsoft.com/en-us/library/ms633573%28v=VS.85%29.aspx和{{3}上给出}}
答案 2 :(得分:0)
本示例(一个包含 2 个文本框的表单)通过在一个文本框上单击左键并在另一个文本框上释放鼠标,将文本框中的文本移动到另一个文本框。如果您注释掉捕获部分,它将停止工作。
Public Class Form1
Dim MousebuttonIsPressed As Boolean = False
Dim TextboxWhereMouseDown As TextBox
Dim TextboxWhereMouseUp As TextBox
Private Sub Form1_mouseup(sender As Object, e As EventArgs) Handles MyBase.MouseUp
MousebuttonIsPressed = False
End Sub
Private Sub Textbox_MouseDown(sender As TextBox, e As MouseEventArgs) Handles TextboxOne.MouseDown, TextboxTwo.MouseDown ' etc for each textbox involved
TextboxWhereMouseDown = sender
If e.Button = MouseButtons.Left Then
MousebuttonIsPressed = True
End If
End Sub
Private Sub Textbox_MouseUp(sender As TextBox, e As MouseEventArgs) Handles TextboxOne.MouseUp, TextboxTwo.MouseUp ' etc.
TextboxWhereMouseUp = sender
If Not (TextboxWhereMouseDown Is TextboxWhereMouseUp) Then
TextboxWhereMouseUp.Text = TextboxWhereMouseDown.Text
TextboxWhereMouseDown.Text = ""
End If
MousebuttonIsPressed = False
End Sub
Private Sub Textbox_MouseEnter(sender As TextBox, e As EventArgs) Handles TextboxOne.MouseEnter, TextboxTwo.MouseEnter ' etc
If MousebuttonIsPressed Then
TextboxWhereMouseUp = sender
End If
End Sub
Private Sub Textbox_MouseMove(sender As TextBox, e As MouseEventArgs) Handles TextboxOne.MouseMove, TextboxTwo.MouseMove ' etc
If (e.Button = System.Windows.Forms.MouseButtons.Left) Then
Dim Contrl As Control = sender
If Contrl.Capture Then
If Not Contrl.ClientRectangle.Contains(e.Location) Then ' to allow selection of text
Contrl.Capture = False
End If
End If
End If
End Sub
End Class