How to move a RichTextBox with mouse
Hi,
I would like to find out, how a RichTextBox can be moved by mouse. I have written some code for it, but it does not work well. The RTB does only move, when the mouse hits its border. The mouse is not really captured, too. It releases the RTB whenever it is moving outside RTB´s area.
Here´s the code:
XAML:
Code:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Canvas Margin="1" Name="Canvas1">
<RichTextBox Canvas.Left="45" Canvas.Top="55" Height="100" Name="RichTextBox1" Width="200" />
</Canvas>
</Grid>
</Window>
VB:
Code:
Class Window1
Private mMouseDownPosition As Point
Private Sub RichTextBox1_PreviewMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles RichTextBox1.PreviewMouseDown
RichTextBox1.CaptureMouse()
mMouseDownPosition = e.GetPosition(Canvas1)
Beep()
End Sub
Private Sub RichTextBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles RichTextBox1.MouseMove
Dim x As Point = e.GetPosition(Canvas1)
If (e.LeftButton = MouseButtonState.Pressed) Then
Canvas.SetLeft(RichTextBox1, Canvas.GetLeft(RichTextBox1) + (x.X - mMouseDownPosition.X))
Canvas.SetTop(RichTextBox1, Canvas.GetTop(RichTextBox1) + (x.Y - mMouseDownPosition.Y))
End If
mMouseDownPosition = x
End Sub
Private Sub RichTextBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles RichTextBox1.MouseUp
RichTextBox1.ReleaseMouseCapture()
End Sub
End Class
Greetings,
TheTree
Re: How to move a RichTextBox with mouse
Try this
vb.net Code:
Public Class Form1
Private intXPos As Integer = 0
Private intYPos As Integer = 0
Private blnIsMoving As Boolean = False
Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDown
intXPos = e.X
intYPos = e.Y
blnIsMoving = True
End Sub
Private Sub RichTextBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseMove
If blnIsMoving Then
RichTextBox1.Top = RichTextBox1.Top - (intYPos - e.Y)
RichTextBox1.Left = RichTextBox1.Left - (intXPos - e.X)
End If
End Sub
Private Sub RichTextBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseUp
blnIsMoving = False
End Sub
End Class
Re: How to move a RichTextBox with mouse
Hi Hack,
thanks for your reply. Your code runs under WindowsForms.
I would like to code a WPF-app, so that RTBs, Lines and other controls can be added and moved by mouse.
Greetings,
TheTree
Re: How to move a RichTextBox with mouse
Re: How to move a RichTextBox with mouse
Hi bflosabre91,
thank you for that link. Good code.
Greetings,
Michael