作為一名新的 C# 程式員,我有很多問題需要解決,尤其是關于MouseEventArgs e及其與MouseButtons.Left的看似不兼容的互動的問題,
我可能對 MouseEventArgs 的真正功能或用法缺乏了解,這是導致此問題的原因。
有人可以解釋為什么我的嘗試不正確,正確的解決方案是什么,以及如何防止將來遇到此類問題?
private void BtnSize_MouseDown(object sender, MouseEventArgs e)
{
// Issue exists here, e == MouseButtons.Left does not work
// why? Isn't the purpose of MouseEventArgs e to track the
// mouse input (aka left click?)
if (e == MouseButtons.Left)
{
// clear canvas
Ball.Loading = true;
while (ballsAdded < 25 && ballsRemoved < 1000)
{
Ball newBall = new Ball(ballRadiusSet);
// Contains bool will force balls to spawn apart from one another
if (!soManyBalls.Contains(newBall))
{
soManyBalls.Add(newBall);
ballsAdded ;
}
else
{
ballsRemoved ;
}
}
foreach (Ball listBall in soManyBalls)
{
listBall.AddBall();
}
// render canvas
Ball.Loading = false;
Text = $"Loaded {ballsAdded} distinct balls with {ballsRemoved} discards";
ballsAdded = 0;
ballsRemoved = 0;
}
if (e == MouseButtons.Right)
{
// clear canvas
Ball.Loading = true;
while (ballsAdded < 25 && ballsRemoved < 1000)
{
Ball newBall = new Ball(ballRadiusSet);
// Invert Contains bool so balls form directly connected to one another
if (soManyBalls.Contains(newBall))
{
soManyBalls.Add(newBall);
ballsAdded ;
}
else
{
ballsRemoved ;
}
}
foreach (Ball listBall in soManyBalls)
{
listBall.AddBall();
}
// render canvas
Ball.Loading = false;
Text = $"Loaded {ballsAdded} distinct balls with {ballsRemoved} discards";
ballsAdded = 0;
ballsRemoved = 0;
}
}
uj5u.com熱心網友回復:
您可以使用包含相關滑鼠按鈕的事件屬性,而不是MouseButtons.Left與事件本身 ( ) 進行比較:e == MouseButtons.Lef
if (e.Button == MouseButtons.Left)
{
// ...
MouseEventArgs不僅包含按下的按鈕,還包含有關滑鼠事件的其他資訊,例如位置。
另請注意,該Button屬性包含所有按下按鈕的資訊。因此,例如,如果左鍵和右鍵都被單擊,但您只想檢查左鍵,則必須比較位模式,例如
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// ...
如果左按鈕與其他按鈕一起單擊,上述條件也將評估為真。
uj5u.com熱心網友回復:
引數e是MouseEventArgs型別的物件。MouseButtons.Left是型別的列舉欄位MouseButtons。此列舉欄位永遠不等于 MouseEventArgs 型別的物件。
private void BtnSize_MouseDown(object sender, MouseEventArgs e)
{
if (e == MouseButtons.Left)
此等式將始終回傳 false。
如果您檢查 MouseEventArgs 的定義,您會發現它有一個屬性MouseEventArgs.Button。此屬性的型別為MouseButtons。以下可能有效:
if (e.Button == MouseButtons.Left)
警告!MouseButtons 是一個帶有 flags 屬性的列舉。這意味著該值可以是幾個列舉值的組合。如果操作員同時按下左右按鈕,則值為:MouseButtons.Left | MouseButtons.Right。因此該陳述句if (e.Button == MouseButtons.Left)將回傳 false。
如果操作員同時按下兩個按鈕,您必須檢查要求如何反應?忽略右鍵并表現得好像只按下了左鍵?
if (e.Button & MouseButtons.Left == MouseButtons.Left)
如果僅按下左按鈕,則回傳 true,但如果左按鈕與其他按鈕一起按下,則回傳 true
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516771.html
標籤:C#表格鼠标事件
下一篇:我必須在方法中處理位圖嗎?
