我希望能够使用空格键来修改鼠标按住时的行为。如果不知道更好,我想象它涉及两个(或三个)事件处理程序之间的某种协调 - mousemove
,keydown
和keyup
。但我想知道是否有一些方法可以在一个事件处理程序中完全处理它 - mousemove
。
示例代码,以了解我希望能够做什么...
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (Keyboard.KeyDown == Keys.Space)
{
/* Do modified behavour for left mouse being held down while
space is also held down */
}
else
{
// Do normal behavour for left mouse being held down
}
}
}
这样的事情是可能的还是我必须使用keydown事件处理程序将空格键的状态保存到类变量并使用鼠标移动处理程序检查它?
答案 0 :(得分:4)
可以使用Control.ModifierKeys& Control.MouseButtons。但只适用于像shift,ctrl和alt这样的kays。
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if ((Control.ModifierKeys & Keys.Shift) != 0)
{
if ((Control.MouseButtons & MouseButtons.Left) != 0)
{ // here you go
}
}
}
答案 1 :(得分:1)
您应该在KeyDown-Event中设置一个变量,并在MouseEvent中检查它:
bool buttonpressed = false;
private void KeyDown_Event(object s, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == KeyCode.Space)
buttonpressed = true;
else
buttonpressed = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (buttonPressed)
{
/* Do modified behavour for left mouse being held down while
space is also held down */
}
else
{
// Do normal behavour for left mouse being held down
}
}
}
答案 2 :(得分:1)
我有一个变量可以跟踪Keys.Space
处于Pressed
状态的时间,然后通过KeyUp
和KeyDown
个事件触发
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
// Check if Key.Space pressed
if(SpacePressed) {
// Do something
}
}
private void KeyPressed_Event(object sender, KeyEventArgs e) {
// Check if Key.Space pressed
if(e.Key == Key.Space) {
SpacePressed = true;
}
}
private void KeyRelease_Event(object sender, KeyEventArgs e) {
// Check if Key.Space pressed
if(e.Key == Key.Space) {
SpacePressed = false;
}
}
答案 3 :(得分:0)
您可以使用PInvoke在User32.dll中调用GetKeyState。