Skip to main content

Microsoft Silverlight

Answered Question Problem with calling CaptureMouse from within a UserControlRSS Feed

(0)

jhndnn
jhndnn

Member

Member

2 points

4 Posts

Problem with calling CaptureMouse from within a UserControl

If I call CaptureMouse(); from within my UserControl I stop getting mouse messages until I let up on the mouse button. If I implement the same logic from inside the root Page it works ok.

 Here's the c# code

namespace SilverlightProject2
{
  public class UserControl1 : Control
  {
    bool _dragging = false;
    Point _start;
    Rectangle _rc;
    FrameworkElement _impRoot;
    public UserControl1()
    {
      System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("SilverlightProject2.UserControl1.xaml");
      _impRoot = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
      _rc = _impRoot.FindName("_rc") as Rectangle;
    }
    protected void cancelDrag()
    {
      _dragging = false;
      ReleaseMouseCapture();
      _rc.Visibility = Visibility.Hidden;
    }
    protected void onMouseLeftButtonDown(object sender, MouseEventArgs e)
    {
      _dragging = true;
      _start = e.GetPosition(this);
      _rc.SetValue<double>(Canvas.TopProperty, _start.Y);
      _rc.SetValue<double>(Canvas.LeftProperty, _start.X);
      _rc.Width = 0;
      _rc.Height = 0;
      _rc.Visibility = Visibility.Visible;
      CaptureMouse();
    }
    protected void onMouseLeftButtonUp(object sender, MouseEventArgs e)
    {
      cancelDrag();
    }
    protected void onMouseMove(object sender, MouseEventArgs e)
    {
      if (_dragging)
      {
        Point pt = e.GetPosition(this);
        _rc.Width = pt.X - _start.X;
        _rc.Height = pt.Y - _start.Y;
      }
    }
  }
}

 

and the XAML

<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="640"
        Height="480"
        Background="LightGray"
         MouseLeftButtonDown="onMouseLeftButtonDown"
         MouseLeftButtonUp="onMouseLeftButtonUp"
         MouseMove="onMouseMove"
        >
  <Rectangle x:Name="_rc" Fill="Green" Visibility="Hidden"/>
</Canvas>
 

 

Vivek Dalvi
Vivek Dalvi

Member

Member

458 points

123 Posts

Microsoft
Answered Question

Re: Problem with calling CaptureMouse from within a UserControl

This is because you are hooking up event handlers on the rootcanvas (Implementationroot) of the control and when you call release/capture you are calling it on user control class. So when you capture mouse (root canvas stops getting mouse events) when you let go mouse button you call release and you start getting mouse events

You could either call release capture on impRoot or you could move event handlers to code and hook them for user control. this.MoveMove += ....

Vivek Dalvi
Program Manager
Microsoft
This post is provided "as-is"
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities