我正在使用MousePosition尝试确定用户在触发MouseDown事件后移动鼠标的方式。问题是我试图使用Point数据类型创建一个起始变量,我只希望这个Point用数据填充一次,但我在MouseDown中有它,所以我可以使用鼠标参数eX和eY来确定MouseDown事件的位置调用。这是我想到的
的一个例子public void panel1_MouseDown(object sender, MouseEventArgs e)
{
Point start = new Point(e.X, e.Y);
}
public void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(MousePosition.X > start.X)
{
Console.WriteLine("you have moved right");
}
}
那么我怎样才能创建该起始变量一次,同时仍然可以访问e鼠标参数。以及如何访问panel1_MouseDown和panel1_MouseMove之间的变量?如果你看到一个更好的替代方案,那就太棒了!谢谢大家的帮助!
答案 0 :(得分:3)
如果您厌恶定义新的类成员(由于某种原因),这是您可能拥有的最少的:
Point? start = null;
public void panel1_MouseDown(object sender, MouseEventArgs e)
{
start = new Point(e.X, e.Y);
}
public void panel1_MouseUp(object sender, MouseEventArgs e)
{
start = null;
}
public void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(start.HasValue)
if(MousePosition.X > start.Value.X)
Console.WriteLine("you have moved right");
}
但为了清晰(和功能),我还有一个额外的布尔变量:
bool mouseIsDown = false;
Point start;
public void panel1_MouseDown(object sender, MouseEventArgs e)
{
start = new Point(e.X, e.Y);
mouseIsDown = true;
}
public void panel1_MouseUp(object sender, MouseEventArgs e)
{
mouseIsDown = false;
}
public void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(mouseIsDown)
if(MousePosition.X > start.X)
Console.WriteLine("you have moved right");
}
答案 1 :(得分:2)
将您的起点声明为私有类变量
Private Point start;
public void panel1_MouseDown(object sender, MouseEventArgs e)
{
this.start = new Point(e.X, e.Y);
}
public void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(MousePosition.X > this.start.X)
{
Console.WriteLine("you have moved right");
}
}