Drag and Drop Windows Forms Button - winforms

I create a new Windows Forms Application. I drag a button on to the form.
I need to drag and drop this button to another location within this form at run time.
any code snippets or links are appreciated.
I spent half an hour searching before coming here.

You can start with something like this:
bool isDragged = false;
Point ptOffset;
private void button1_MouseDown( object sender, MouseEventArgs e )
{
if ( e.Button == MouseButtons.Left )
{
isDragged = true;
Point ptStartPosition = button1.PointToScreen(new Point(e.X, e.Y));
ptOffset = new Point();
ptOffset.X = button1.Location.X - ptStartPosition.X;
ptOffset.Y = button1.Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
private void button1_MouseMove( object sender, MouseEventArgs e )
{
if ( isDragged )
{
Point newPoint = button1.PointToScreen(new Point(e.X, e.Y));
newPoint.Offset(ptOffset);
button1.Location = newPoint;
}
}
private void button1_MouseUp( object sender, MouseEventArgs e )
{
isDragged = false;
}

Related

"Microsoft Blend"-like continuous Drag

Microsoft Blend allows changing numeric values of properties like Left, Top etc. through continuous drag. User clicks in the property value box, keeps the button down and drags left or right to decrease/increase the value. Simple.
The special thing about it is that if cursor reaches the left or right end of the screen and user still wants to drag more, they can continue dragging and the cursor will start over from the other end of the screen.
I'm trying to do this in one of my WPF applications using Thumb control. Using DragDetla event, if I find that the Thumb has reach the edge of the screen, I set its position to the far end. But this makes the value of e.HorizontalChange as big as the width of entire screen. How can I change Thumb's position during drag without affecting horizontal change value?
I have realized this in a WPF control by using a textbox and subscribing to events such as:
PreviewMouseDown
MouseUp and
MouseMove
MouseEnter
The drag until you reach screen limits requires a mouse capture or call to CaptureMouse method available on any UIElement. On the other side, you need to release the mouse at some point which requires a call of the ReleaseMouseCapture method. The solution could go like this:
Declare an enumeration to model the drag direction
internal enum MouseDirections
{
None,
LeftRight,
UpDown
}
Declare a class to keep trak of mouse origin (first location) and current location:
internal class MouseIncrementor
{
private MouseDirections _enumMouseDirection = MouseDirections.None;
private Point _objPoint;
private readonly Point _initialPoint;
public MouseIncrementor(Point objPoint, MouseDirections enumMouseDirection)
{
_objPoint = objPoint;
_initialPoint = _objPoint;
_enumMouseDirection = enumMouseDirection;
}
public MouseDirections MouseDirection
{
get
{
return _enumMouseDirection;
}
protected set
{
_enumMouseDirection = value;
}
}
public Point InitialPoint
{
get
{
return _initialPoint;
}
}
public Point Point
{
get
{
return _objPoint;
}
set
{
_objPoint = value;
}
}
internal MouseDirections SetMouseDirection(Point pos)
{
double deltaX = this.Point.X - pos.X;
double deltaY = this.Point.Y - pos.Y;
if (Math.Abs(deltaX) > Math.Abs(deltaY))
MouseDirection = MouseDirections.LeftRight;
else
{
if (Math.Abs(deltaX) < Math.Abs(deltaY))
MouseDirection = MouseDirections.UpDown;
}
return MouseDirection;
}
}
I have a custom control that contains a TextBox named _PART_TextBox:
TextBox _PART_TextBox;
...and field for the MouseIncrementor:
MouseIncrementor _objMouseIncr;
...these are wired up like this:
_PART_TextBox.MouseEnter += _PART_TextBox_MouseEnter;
_PART_TextBox.GotKeyboardFocus += _PART_TextBox_GotKeyboardFocus;
_PART_TextBox.LostKeyboardFocus += _PART_TextBox_LostKeyboardFocus;
_PART_TextBox.MouseMove += _PART_TextBox_MouseMove;
_PART_TextBox.MouseUp += _PART_TextBox_MouseUp;
_PART_TextBox.PreviewMouseDown += _PART_TextBox_PreviewMouseDown;
_PART_TextBox.LostMouseCapture += _PART_TextBox_LostMouseCapture;
and a number of event handlers are required to get this to work:
private void _PART_TextBox_LostMouseCapture(object sender, MouseEventArgs e)
{
_objMouseIncr = null;
}
private void _PART_TextBox_MouseUp(object sender, MouseButtonEventArgs e)
{
if (_objMouseIncr != null)
{
var mouseUpPosition = GetPositionFromThis(e);
if (_objMouseIncr.InitialPoint.Equals(mouseUpPosition))
{
_PART_TextBox.Focus();
}
}
_PART_TextBox.ReleaseMouseCapture();
_objMouseIncr = null;
}
private void _PART_TextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (IsKeyboardFocusWithin == false)
{
_objMouseIncr = new MouseIncrementor(this.GetPositionFromThis(e), MouseDirections.None);
e.Handled = true;
}
}
private void _PART_TextBox_MouseMove(object sender, MouseEventArgs e)
{
// nothing to do here
if (_objMouseIncr == null)
return;
if (e.LeftButton != MouseButtonState.Pressed)
return;
if (CanIncreaseCommand() == false && CanDecreaseCommand() == false)
{
// since we can't parse the value, we are out of here, i.e. user put text in our number box
_objMouseIncr = null;
return;
}
var pos = GetPositionFromThis(e);
double deltaX = _objMouseIncr.Point.X - pos.X;
double deltaY = _objMouseIncr.Point.Y - pos.Y;
if (_objMouseIncr.MouseDirection == MouseDirections.None)
{
// this is our first time here, so we need to record if we are tracking x or y movements
if (_objMouseIncr.SetMouseDirection(pos) != MouseDirections.None)
_PART_TextBox.CaptureMouse();
}
if (_objMouseIncr.MouseDirection == MouseDirections.LeftRight)
{
if (deltaX > 0)
OnDecrement(LargeStepSize);
else
{
if (deltaX < 0)
OnIncrement(LargeStepSize);
}
}
else
{
if (_objMouseIncr.MouseDirection == MouseDirections.UpDown)
{
if (deltaY > 0)
{
if (CanIncreaseCommand() == true)
OnIncrease();
}
else
{
if (deltaY < 0)
{
if (CanDecreaseCommand() == true)
OnDecrease();
}
}
}
}
_objMouseIncr.Point = GetPositionFromThis(e);
}
private Point GetPositionFromThis(MouseEventArgs e)
{
return this.PointToScreen(e.GetPosition(this));
}
private void _PART_TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
_objMouseIncr = null;
(sender as TextBox).Cursor = Cursors.ScrollAll;
}
private void _PART_TextBox_MouseEnter(object sender, MouseEventArgs e)
{
if (IsMouseDragEnabled == false)
return;
if (IsKeyboardFocusWithin)
(sender as TextBox).Cursor = Cursors.IBeam;
else
(sender as TextBox).Cursor = Cursors.ScrollAll;
}
private void _PART_TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
_objMouseIncr = null;
(sender as TextBox).Cursor = Cursors.IBeam;
}
The full project is located here: https://github.com/Dirkster99/NumericUpDownLib
Please let me know if I am missing something or if there are additional questions.

WFP TranslateTransform Error

I am working on a drawing project. In which I have t create a draggable window where a user can Click on any Object and move it to different positions like we do in PhotoShop with our layers.
Programme I write is working perfectly for the One object on the screen and I can move to any position I want by simply dragging it. But when the number of objects is increased then it is causing a very weird problem. When I click on the any of the objects it creates a cluster of the all the objects on the windows and starts applying the transformation to the whole cluster.
Note : All the object are the Images and Container is Canvas.
Here are some images and code I am using.
private Point _currentPoint;
private Point _ancherPoint;
private bool _isInDrag = false;
private TranslateTransform _transform = new TranslateTransform();
private Image _element;
private void DropList_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
{
_element = FindAnchestor<Image>( ( DependencyObject )e.OriginalSource );
if( _element != null )
{
_ancherPoint = e.GetPosition( DropList );
_isInDrag = true;
_element.CaptureMouse();
e.Handled = true;
}
}
private void DropList_MouseMove( object sender, MouseEventArgs e )
{
if( _isInDrag )
{
_currentPoint = e.GetPosition( DropList );
_transform.X += ( _currentPoint.X - _ancherPoint.X );
_transform.Y += ( _currentPoint.Y - _ancherPoint.Y );
Lbl.Content = _element.Source.ToString();
Source on which transfrom is going to happen
_element.RenderTransform = _transform;
_ancherPoint = _currentPoint;
}
}
private void DropList_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
{
if( _isInDrag )
{
_element.ReleaseMouseCapture();
_isInDrag = false;
e.Handled = true;
}
}
private static T FindAnchestor<T>( DependencyObject current ) where T : DependencyObject
{
do
{
if( current is T )
{
return ( T )current;
}
current = VisualTreeHelper.GetParent( current );
}
while( current != null );
return null;
}
This is the single object I can move it to any place I want easily without any mess up.
Here I have three objects. when I click any of them they make a cluster and start moving together.
The problem is that you are using the same TranslateTransform instance for all elements. You should instead create a new instance for each element, either when you create the element, or e.g. in the MouseDown handler:
private void DropList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_element = FindAnchestor<Image>((DependencyObject)e.OriginalSource);
if (_element != null)
{
var point = e.GetPosition((IInputElement)sender);
_isInDrag = true;
_element.CaptureMouse();
_element.RenderTransform = new TranslateTransform(point.X, point.Y); // here
e.Handled = true;
}
}
And use it when moving:
private void DropList_MouseMove(object sender, MouseEventArgs e)
{
if (_isInDrag)
{
var point = e.GetPosition((IInputElement)sender);
var transform = (TranslateTransform)_element.RenderTransform;
transform.X = point.X;
transform.Y = point.Y;
}
}

How do I hittest for a TabControl tab?

Given a point relative to a Page, how do I hittest for a TabControl's tab? VisualTreeHelper.HitTest gives me the contents, but when I go up the visual tree I see nothing that would tell me that I have actually hit a tab. I don't even see the tab control itself.
public class ViewManipulationAgent : IDisposable
{
private const int _limit = 125;
private INavigationService _navigationService;
private FrameworkElement _container;
private FrameworkElement _element;
private TranslateTransform _translate;
private IInputElement _touchTarget;
// When I use this object,
// a_container is the main Frame control in my application.
// a_element is a page within that frame.
public ViewManipulationAgent(FrameworkElement a_container, FrameworkElement a_element)
{
_navigationService = a_navigationService;
_container = a_container;
_element = a_element;
// Since I set IsManipulationEnabled to true all touch commands are suspended
// for all commands on the page (a_element) unless I specifically cancel (see below)
_element.IsManipulationEnabled = true;
_element.PreviewTouchDown += OnElementPreviewTouchDown;
_element.ManipulationStarting += OnElementManipulationStarting;
_element.ManipulationDelta += OnElementManipulationDelta;
_element.ManipulationCompleted += OnElementManipulationCompleted;
_translate = new TranslateTransform(0.0, 0.0);
_element.RenderTransform = _translate;
}
// Since the ManipulationStarting doesn't provide position I capture the position
// here and then hit test elements to find any controls for which I want to bypass
// manipulation.
private void OnElementPreviewTouchDown(object sender, TouchEventArgs e)
{
var position = e.GetTouchPoint(_element).Position;
_touchTarget = null;
HitTestResult result = VisualTreeHelper.HitTest(_element, position);
if (result.VisualHit == null)
return;
var button = VisualTreeHelperEx.FindAncestorByType<ButtonBase>(result.VisualHit) as ButtonBase;
if (button != null)
{
_touchTarget = button;
return;
}
var slider = VisualTreeHelperEx.FindAncestorByType<Slider>(result.VisualHit) as Slider;
if (slider != null)
{
_touchTarget = slider;
return;
}
}
// Here is where I cancel manipulation if a specific touch target was found in the
// above event.
private void OnElementManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
if (_touchTarget != null)
{
e.Cancel(); // <- I have to cancel manipulation or the buttons and other
// controls cannot be manipulated by the touch interface.
return;
}
e.ManipulationContainer = _container;
}
private void OnElementManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
var element = e.Source as FrameworkElement;
if (element == null)
return;
var translate = _translate.X + e.DeltaManipulation.Translation.X;
if (translate > _limit)
{
GoBack();
translate = _limit;
}
if (translate < -_limit)
{
GoForward();
translate = -_limit;
}
_translate.X = translate;
}
private void GoForward()
{
var navigationService = ServiceLocator.Current.GetInstance<INavigationService>();
navigationService.GoForward();
}
private void GoBack()
{
var navigationService = ServiceLocator.Current.GetInstance<INavigationService>();
navigationService.GoBack();
}
private void OnElementManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
_touchTarget = null;
_translate.X = 0;
}
public void Dispose()
{
_element.PreviewTouchDown -= OnElementPreviewTouchDown;
_element.ManipulationStarting -= OnElementManipulationStarting;
_element.ManipulationDelta -= OnElementManipulationDelta;
_element.ManipulationCompleted -= OnElementManipulationCompleted;
}
}

Simulating a Drag/Drop event in WPF

I want to simulate a drag/drop event in WPF.
For this I'll need to gain access to the data stored in the "Drag/Drop buffer" and also I'll need to create a DragEventArgs.
I noticed that the DragEventArgs is sealed and has no public ctor.
So my questions are:
1. how can I create an instance of DragEventArgs?
2. How can I gain access to the drag/drop buffer?
i recently do this! i simulated drag/drop with MouseDown, MouseMove and MouseUp events. for example for my application, i have some canvases that i want to drag and drop them. every canvas has an id. in MouseDown event, i buffer its id and use it in MouseMove and MouseUp event. Desktop_Canvas is my main Canvas that contains some canvases. these canvases are in my dictionary (dic).
here is my code:
private Dictionary<int, Win> dic = new Dictionary<int, Win>();
private Point downPoint_Drag = new Point(-1, -1);
private int id_Drag = -1;
private bool flag_Drag = false;
public class Win
{
public Canvas canvas = new Canvas();
public Point downpoint = new Point();
public Win()
{
canvas.Background = new SolidColorBrush(Colors.Gray);
}
}
private void Desktop_Canvas_MouseMove(object sender, MouseEventArgs e)
{
try
{
Point movePoint = e.GetPosition(Desktop_Canvas);
if (flag_Drag && downPoint_Drag != new Point(-1, -1))
{
double dy1 = movePoint.Y - downPoint_Drag.Y, x = -1, dx1 = movePoint.X - downPoint_Drag.X, y = -1;
downPoint_Drag = movePoint;
if (x == -1)
x = Canvas.GetLeft(dic[id_Drag].canvas) + dx1;
if (y == -1)
y = Canvas.GetTop(dic[id_Drag].canvas) + dy1;
Canvas.SetLeft(dic[id_Drag].canvas, x);
Canvas.SetTop(dic[id_Drag].canvas, y);
}
}
catch
{
MouseEventArgs ee = new MouseEventArgs((MouseDevice)e.Device, 10);
Desktop_Canvas_MouseLeave(null, ee);
}
}
private void Desktop_Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
try
{
downPoint_Drag = new Point(-1, -1);
id_Drag =-1;
flag_Drag = false;
}
catch
{
MouseEventArgs ee = new MouseEventArgs((MouseDevice)e.Device, 10);
Desktop_Canvas_MouseLeave(null, ee);
}
}
private void Desktop_Canvas_MouseLeave(object sender, MouseEventArgs e)
{
MouseButtonEventArgs ee = new MouseButtonEventArgs((MouseDevice)e.Device, 10, MouseButton.Left);
Desktop_Canvas_MouseLeftButtonUp(null, ee);
}
void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
downPoint_Drag = e.GetPosition(Desktop_Canvas);
int hoverId = HoverWin(downPoint_Drag);
flag_Drag = true;
id_Drag = hoverId;
dic[id_Drag].downpoint = new Point(downPoint_Drag.X, downPoint_Drag.Y);
}
private int HoverWin(Point p)
{
foreach (int i in dic.Keys)
{
if (dic[i].canvas.IsMouseOver)
return i;
}
return -1;
}

Change the location of the window form in c#?

In window application, using c# i created one form and put visible false minimize, maximize button and formborder to none, i place one panel at top of the form, in that panel i place close, minimize buttons. Now how can i drag the window form. Any reference please. my code is
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.FormBorderStyle = FormBorderStyle.None;
Thank you.
Simply register the MouseDown, MouseMove and MoueUp events for your Panel
bool MouseDownFlag = false;
Point start = new Point(0, 0);
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
start = new Point(e.X, e.Y);
MouseDownFlag = true;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (MouseDownFlag)
{
Point newPoint = new Point();
newPoint.X = this.Location.X - (start.X - e.X);
newPoint.Y = this.Location.Y - (start.Y - e.Y);
this.Location = newPoint;
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
MouseDownFlag = false;
}

Resources