2011-10-28 33 views
1

マウスの左ボタンを押したままマウスを動かすと、コントロールを更新する必要があります。通常、単にe.Buttonプロパティをチェックするだけですが、MouseEnterイベントでは使用できません。左クリックが押されたときにのみマウス移動イベントをキャプチャする

void MyControl_MouseEnter(object sender, EventArgs e) 
    { 
     // MouseEventArgs needed to check this 

     // if (e.Button == MouseButtons.Left) 
     // { 
     //  update MyControl 
     // } 
    } 

これはどのように達成しますか?

+2

は、マウスボタンが押されたときに/ MouseDownイベント&MouseUpイベントで発売、その後、あなたのコードをチェックインのget /クリアフラグを設定detechでした:基本的な考え方は次のように、唯一のマウスダウンとのmouseup間のMouseMoveをキャプチャすることです上記? – jklemmack

答えて

5

は静的Control.MouseButtonsプロパティを使用します。たとえば:

private void panel1_MouseEnter(object sender, EventArgs e) { 
     if (Control.MouseButtons == MouseButtons.Left) { 
      // etc... 
     } 
    } 

これが軌道に乗ることは非常に困難で、どんなユーザーがマウスボタンが押さ取得する上でクリックすると、発射からコントロールのMouseEnterイベントを防止し、マウスをキャプチャしようとしています。また、ユーザーにとって完全に発見できないUIです。より良いマウストラップを検討してください。

2

ここでは、それを行う(粗い)方法があります。マウスをbutton1にドラッグすると、フォームのタイトルテキストがマウスボタンが押されたものに変更されます。 Control.MouseButtonsを参照すると、どのボタンが押されているかを確認できます。 MSDNに関するさらに詳しい情報があります。

public partial class Form1 : Form 
    { 
     MouseButtons _buttons; 

     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private void button1_MouseMove(object sender, MouseEventArgs e) 
     { 
      if (_buttons != System.Windows.Forms.MouseButtons.None) 
      { 
       this.Text = _buttons.ToString(); 
      } 
     } 

     private void Form1_MouseMove(object sender, MouseEventArgs e) 
     { 
      _buttons = Control.MouseButtons; 
     } 
    } 
+0

+1フォームやUserControlレベルでMouseDownやMouseUpイベントではなくMouseMoveを使用した理由は何ですか? –

1

私はここのSO上の別の質問に答えを見つけた:あなたはメッセージフィルタを使用する必要があります

How can I detect a held down mouse button over a PictureBox?

IMessageFilterインターフェイスのを実装し、Application.AddMessageFilterを使用してインスタンスを割り当てます。

あなたは自分でWindowsメッセージを解釈する必要があります...それは難しいものではありませんが、何らかの作業が必要です。

実装は次のようになります。

 if (m.Msg == 0x200) 
     { 
      int x, y; 
      x = m.LParam.ToInt32() & 0xFFFF; 
      y = m.LParam.ToInt32() >> 16; 
      if ((m.WParam.ToInt32() & 2) != 0) 
      { 
       // here, the left mouse button is pressed, and you can use the coords 
       // and see if the mouse is over the control you want. 
      } 
     } 
1

今日はこのようなことを実装しましたが、Chromeでのみテストされましたが、うまく機能します。

var image = document.getElementById('my_image'); 
image.addEventListener('mousedown', function(e) { 
    e.currentTarget.addEventListener('mousemove', doMyStuff); 
}); 
image.addEventListener('mouseup', function(e) { 
    e.currentTarget.removeEventListener('mousemove', doMyStuff); 
}); 

function doMyStuff(e) { 
    // do what you want, the mouse is moving while the user is holding the button down 
} 
+0

と同じように、e.currentTarget.addEventListenerをimage.addEventListenerと簡単に置き換えることができますが、大したことはわかりません。しかし、便利なパラメータから引き出すのは、クロージャを使うよりも効率的かもしれません。 – RobP

関連する問題