How to clear a textbox if i drag the text out - vb.net

I have code to drag files into a textbox, but I would also like to have code to drag the file out of the textbox, thus clearing it.
Anybody have any ideas?

You can use the DoDragDrop method to do a drag & drop operation. It returns a DragDropEffects value that specifies if the data actually has been dropped somewhere in which case you can clear the text box.
Since a drag & drop operation shouldn't start before the mouse has been moved a bit while pressing the mouse button you need to check for that in the MouseDown and MouseMove events. SystemInformation.DragSize tells you how far the mouse should be moved before a drag & drop operation starts.
In the MouseDown event check if you actually want to start a drag (i.e left button is pressed and text box actually contains text). Then create a rectangle using the mouse location and the size given by SystemInformation.DragSize. In the MouseMove event check if the mouse is dragged outside the rectangle and call DoDragDrop:
Private _dragStart As Boolean
Private _dragBox As Rectangle
Private Sub srcTextBox_MouseDown(sender As Object, e As MouseEventArgs) Handles srcTextBox.MouseDown
' a drag starts if the left mouse button is pressed and the text box actually contains any text
_dragStart = e.Button = MouseButtons.Left And Not String.IsNullOrEmpty(srcTextBox.Text)
If _dragStart Then
Dim dragSize As Size = SystemInformation.DragSize
_dragBox = New Rectangle(New Point(e.X - (dragSize.Width \ 2),
e.Y - (dragSize.Height \ 2)), dragSize)
End If
End Sub
Private Sub srcTextBox_MouseUp(sender As Object, e As MouseEventArgs) Handles srcTextBox.MouseUp
_dragStart = False
End Sub
Private Sub srcTextBox_MouseMove(sender As Object, e As MouseEventArgs) Handles srcTextBox.MouseMove
If Not _dragStart Or
(e.Button And MouseButtons.Left) <> MouseButtons.Left Or
_dragBox.Contains(e.X, e.Y) Then Return
Dim data As New DataObject()
data.SetData(srcTextBox.Text)
' you can optionally add more formats required by valid drag destinations:
' data.SetData(DataFormats.UnicodeText, Encoding.Unicode.GetBytes(srcTextBox.Text))
' data.SetData("UTF-8", Encoding.UTF8.GetBytes(srcTextBox.Text))
' data.SetData("UTF-32", Encoding.UTF32.GetBytes(srcTextBox.Text))
Dim dropEffect As DragDropEffects = srcTextBox.DoDragDrop(data, DragDropEffects.Move)
If (dropEffect = DragDropEffects.Move) Then
srcTextBox.Text = ""
End If
_dragStart = False
_dragBox = Rectangle.Empty
End Sub
Private Sub destTextBox_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles destTextBox.DragOver
If e.Data.GetDataPresent(GetType(String)) Then
e.Effect = e.AllowedEffect And DragDropEffects.Move
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub destTextBox_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles destTextBox.DragDrop
If e.Data.GetDataPresent(GetType(String)) Then
destTextBox.Text = e.Data.GetData(GetType(String)).ToString()
End If
End Sub
Dragging the mouse in a TextBox usually starts text selection. The above code changes this behavior. Users can't use the mouse any more to select text. This is obviously not a good idea since users wouldn't expect that. To allow both text selection with the mouse and dragging you need to control the selection mechanism. This means you need to create your own text box class.
I would suggest a different approach: Use a label that shows the value as the dragging source and/or destination. To allow editing you can create a hidden text box. If the user double clicks on the label you hide the label and show the text box. After the user finishes editing (by hitting enter or cancel) or if the text box looses focus you hide the text box and show the label again.

Check out the DragLeave Event on the TextBox
Easiest way will probably be to store it as a variable or in clip board if leaving app.
Private Sub TheTextBox_DragLeave(sender As System.Object, e As System.EventArgs) Handles TheTextBox.DragLeave
Clipboard.SetText(TheTextBox.Text)
TheTextBox.Clear() 'Optional
End Sub
Then you'll need to code what happens when you mouse up of course, or drag into or whatever. You could clear the textbox in one of these steps. Depends on your implementation.

Related

Enable other event while dragging an object

I'm developing a console where I want to drag a button to a grid:
To drag the button, I use the following procedure:
Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button
Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
drag = True
btn = CType(sender, Button)
ptX = e.X : ptY = e.Y
End Sub
Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
If drag Then
btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
Me.Refresh()
End If
End Sub
Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
drag = False
End Sub
So far, so good! This works fine for that matter.
However, I'm trying to highlight the cell while hoovering the button on it like this:
To do so, I tried to do the following:
Private Sub CellA1_MouseHover(sender As Object, e As EventArgs) Handles CellA1.MouseHover
If drag Then
CellA1.BackColor = Color.Red
End If
End Sub
Of course I can't do that, unless I, somehow, enable the CellA1.MouseHover event while dragging the MoveButton.
Can anyone help me with this?
If, however, you're having a struggling will to help me further, my last goal is to place the MoveButton on the red cell place:
But feel free to don't help me at all with this part of the procedure since I have no code to perform this yet.
Any help will be very appreciated. And, as always, thank you all in advance.
Since your mouse is not actually on the PictureBox when you drag the button it will never raise any mouse events. What you can do instead is to call the GetChildAtPoint() method of your form to get the control behind the button. Once you have that just verify that the name starts with "Cell" and change the back color.
To snap to the cell's location you'll need to indicate to MouseUp which cell we're currently at. Simply store the cell control in a variable and you can then just set yourButton.Location = currentCell.Location
Here are the changes I've made to your code, commented for clarity:
Public drag As Boolean = False
Public ptX As Integer = 0
Public ptY As Integer = 0
Public btn As Button
Public prevCtrl As Control = Nothing 'Store the previous Cell the button was dragged over.
' We need this to be able to reset the BackColor of the Cell,
' and also so that you can snap to its location once you drop the button.
Private Sub MoveButton_MouseDown(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseDown
'No changes made here.
drag = True
btn = CType(sender, Button)
ptX = e.X : ptY = e.Y
End Sub
Private Sub MoveButton_MouseMove(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseMove
If drag Then
btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
'Go 1 pixel up, or else GetChildAtPoint() will return the button instead of the control behind it.
Dim LookPoint As Point = Point.Subtract(btn.Location, New Size(0, 1))
'Get the control located below/behind the button.
Dim ControlBelow As Control = Me.GetChildAtPoint(LookPoint, GetChildAtPointSkip.Invisible Or GetChildAtPointSkip.Disabled) 'Ignore invisible or disabled controls.
'Check so that the previous cell is not also the current cell. If they're the same then we won't change anything.
If prevCtrl IsNot ControlBelow Then
'Ok, the current cell and the previous cell are not the same.
'Now check if there was any previous cell at all.
If prevCtrl IsNot Nothing Then
'There was a previous cell, but since the button
'is no longer hovering over it we reset its BackColor.
prevCtrl.BackColor = Color.White
prevCtrl = Nothing
End If
'Check that there infact is a control behind the button,
'and also check that its name starts with "Cell".
If ControlBelow IsNot Nothing AndAlso ControlBelow.Name.StartsWith("Cell", StringComparison.OrdinalIgnoreCase) Then
'The control behind the button is a valid Cell. Change its BackColor.
ControlBelow.BackColor = Color.Red
prevCtrl = ControlBelow 'The previous cell is now the current cell.
End If
End If
'Me.Refresh() - this is a very unnecessary call, it will just eat CPU. The form does not need to be redrawn at this point.
End If
End Sub
Private Sub MoveButton_MouseUp(sender As Object, e As MouseEventArgs) Handles MoveButton.MouseUp
'Check if we dragged the button. At this point prevCtrl is the current cell (if it's not Nothing).
If drag = True AndAlso prevCtrl IsNot Nothing Then
btn.Location = prevCtrl.Location 'Snap to the cell's location.
prevCtrl.BackColor = Color.White 'Reset the cell's BackColor.
prevCtrl = Nothing 'Reset this since we're no longer dragging the button.
End If
drag = False
End Sub
And it works like a charm!

vb.net add values from listbox to textbox via drag&drop AND via double click

I'm struggling with some functionality I want to use on my Windows form.
( Just for info, this is for an AutoDesk Inventor AddIn. )
This is my form layout.
The current workflow
The top 4 list-boxes are filled with available parameter names. The user chooses the parameter(s) he/she wants to use and drags and drops it into one of the driving parameter text-boxes ( marked with the <1> label ).
The code that relates to the drag and drop operations
Private Sub lstTemp_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles lbModelParameters.MouseDown,
lbUserParameters.MouseDown,
lbReferenceParameters.MouseDown,
lbLinkedParameters.MouseDown
' In order to access a specific item in a listbox.itemcollection, you must think of it
' as an array of data or a collection and access it in the same manner by always
' letting VB know which item you intend to use by identifying it with its index location
' within the collection. And this is better than taking up basket weaving :-)
lbModelParameters.DoDragDrop(sender.Items(sender.SelectedIndex()).ToString, DragDropEffects.Move)
End Sub
Private Sub txtTemp_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragEnter,
tbParameter2.DragEnter,
tbParameter3.DragEnter,
tbParameter4.DragEnter,
tbParameter5.DragEnter
'Check the format of the incoming data and accept it if the destination control is able to handle
' the data format
'Data verification
If e.Data().GetDataPresent(DataFormats.Text) Then
e.Effect() = DragDropEffects.Move
Else
e.Effect() = DragDropEffects.None
End If
End Sub
Private Sub txtTemp_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragDrop,
tbParameter2.DragDrop,
tbParameter3.DragDrop,
tbParameter4.DragDrop,
tbParameter5.DragDrop
'This procedure receives the dragged data once it passes the data verification handled by the DragEnter method
'Drops the data onto the destination control
sender.Text() = e.Data().GetData(DataFormats.Text).ToString()
End Sub
New functionality
Now I would like to decrease the user mouse movement for ergonomic reasons and speed. But I would also like to keep to the drag and drop functionality. As it can overwrite a value that has already been added by the user.
I would like to be able to DoubleClick a item in the listbox, and that item should be added to the first empty textbox. I named my textboxes with a number so it's easy to loop over them all to check if it's empty.
I tried doing it with this code, but my double click event never gets fired. It always goes to the drag and drop. How do you do handle this, that the double click gets fired instead of drag drop?
Private Sub ParameterAddDoubleClick(sender As Object, e As EventArgs) _
Handles lbModelParameters.DoubleClick,
lbUserParameters.DoubleClick,
lbReferenceParameters.DoubleClick,
lbLinkedParameters.DoubleClick
Dim oControl As Windows.Forms.ListBox
oControl = DirectCast(sender, Windows.Forms.ListBox)
' Add line in likedparameters listbox
If oControl.SelectedIndex <> -1 Then
' Loop trough all the controls to see if one is empty
' if it's empty add parameter, else go to next
' if all textboxes are used do nothing.
For i = 1 To 6
Dim oTextbox As Windows.Forms.TextBox =
CType(gbDrivingParameters.Controls("tbParameter" & i),
Windows.Forms.TextBox)
If oTextbox.TextLength = 0 Then
' Add the sender item into the linked listbox
oTextbox.Text = oControl.Items.Item(oControl.SelectedIndex)
End If
Next
End If
End Sub
I hope my question is clear, and well prepared. If there is additional information needed, please let me know in a comment.
Mousedown triggers the DoDragDrop, wich stops the doubleclick-event from firing.
To identify if a user doubleclicks or wants to perform a dragdrop, consider the following:
Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Determine whether we are performing a drag operation OR a double click
If e.Clicks = 1 Then
TextBox1.Text = "mousedown"
Else
TextBox1.Text = "dblclick"
End If
End Sub

Determine which textbox on winform has cursor in it

I am working on a Windows Form via VB.net. The form contains two textboxes and an onscreen keyboard that I have programmed myself.
How can I determine which textbox the cursor is currently in, so that the onscreen keyboard will type in the correct textbox?
The application is meant to be entirely touch based.
I'm going to guess that your onscreen keyboard is a series a buttons representing a keyboard.
Since you have two text boxes, you have to have a flag for both text boxes to indicate that they have focus, and when one has it the other doesn't.
Private Sub TextBox1_GotFocus(sender as Object, e as EventArgs) _
Handles TextBox1.GotFocus
// These flags are class level variables
textbox1HasFocus = true;
textbox2HasFocus = false;
End Sub
Private Sub TextBox2_GotFocus(sender as Object, e as EventArgs) _
Handles TextBox2.GotFocus
// These flags are class level variables
textbox2HasFocus = true;
textbox1HasFocus = false;
End Sub
For your keyboard events
Private Sub KeyBoard_Click(sender As Object, e As EventArgs) Handles ButtonA.Click, ButtonB.Click, ButtonC.Click, etc...
' I don't know how your using your keyboard, but buttonClickLetter could be determined in multiple ways. I would use either the Name of the control or even the Tag property for retrieving which letter to use
String buttonClickLetter = DirectCast(sender, Button).Tag.ToString()
If textbox1HasFocus Then
TextBox1.Text += buttonClickLetter
ElseIf textbox2HadFocus
TextBox2.Text += buttonClickLetter
End If
End Sub

How to make menustrip drop-down appear ABOVE the button in Visual Basic

In Visual Studio, how do you make a drop-down for a menu-strip button appear ABOVE the button, instead of below it, regardless of whether or not the form is on the bottom of the screen (I.e. windows automatically places the drop-down above the button if the form is on the bottom of the screen, I want to do this regardless of whether or not it is on the bottom.)
This may help point you in the right direction:
Private Sub HandleMouseUp(Byval Control as Object, _
Byval e As System.Windows.Forms.MouseEventArgs)
' Checking the Mouse right Button
If e.Button = MouseButtons.Right Then
Control.ContextMenu.Show(Control, New Point(e.X,e.Y))
End if
End sub
You can then call this sub from any object's mouseup event:
Private Sub button1_MouseUp(Byval Sender as Object, _
Byval e As System.Windows.Forms.MouseEventArgs) _
Handles button1.MouseUp
HandleMouseUp(button1,e)
End sub
You would then simply change the "New Point (e.X, e.Y)" to suit your needs. You could create a more uniform look by placing the x and y coordinates of your control and manipulating as needed. This article is where I am pulling from: http://www.codeproject.com/Articles/8756/Context-Menu-and-Event-Handling-in-Visual-Basic-NE.
Hope this helps.

How can I place/drop an image evertime you click the mouse button using vb.net?

I looked at "How do I place an image with a mouse-click in Javascript?" but it had a small snippet of Java; immensely larger than my knowledge of Java. And that is the closest I've come to finding an answer in the past week.
Here's what I would like to do (don't know if its even possible):
I have a panel and a toolstrip with 3 buttons. Each button represents a different image. I want to click on a button (once) and then move into the panel and everytime I click the mouse button it drops the image where ever I clicked. This only ends when either I click back on the same button or one of the other buttons. I do not want to drag an image into the panel each time. In other words the button stays depressed and the event/action stays active.
Any help would be greatly appreciated.
Here is an example application. It's just a form with a ToolStrip on it, along with a couple of buttons with an image added to each button. The key property for each button is CheckOnClick=True, which will keep the button pressed down.
There isn't a radio button like feature for ToolStrips, so you have to "uncheck" the other ToolStripButtons yourself, which I have handled in the ItemClicked event.
Public Class Form1
Private _ActiveImage As Image = Nothing
Private Class ImagePoint
Public Location As Point
Public Image As Image
Public Sub New(ByVal image As Image, ByVal location As Point)
Me.Image = image
Me.Location = location
End Sub
End Class
Private _Images As New List(Of ImagePoint)
Public Sub New()
InitializeComponent()
Me.DoubleBuffered = True
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
For Each imageItem As ImagePoint In _Images
e.Graphics.DrawImage(imageItem.Image, imageItem.Location)
Next
End Sub
Private Sub ToolStrip1_ItemClicked(ByVal sender As Object, ByVal e As ToolStripItemClickedEventArgs) Handles ToolStrip1.ItemClicked
For Each toolButton As ToolStripButton In ToolStrip1.Items.OfType(Of ToolStripButton)()
If toolButton.CheckOnClick Then
If e.ClickedItem.Equals(toolButton) Then
_ActiveImage = e.ClickedItem.Image
Else
toolButton.Checked = False
End If
End If
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If _ActiveImage IsNot Nothing AndAlso e.Button = MouseButtons.Left Then
_Images.Add(New ImagePoint(_ActiveImage, e.Location))
Me.Invalidate()
End If
End Sub
End Class
This example just uses a simple class to hold which image was placed at what location and the paint event just loops through the list and paints the image.
If deleting images is in your future, then you would have to call e.Graphics.Clear(Color.White) before painting any images.
For the button UI, check out the alternate style for radio buttons/check boxes. They have a "toggle button" mode which sounds like exactly what you need.
You could go through the motions of detecting mouse down events on the panel, getting the coordinates, creating an image control, and placing a copy of the image in it, but there's a better approach.
Fill the panel with a single image control (fill so that it handles resizes, the image control should always be the same size as the panel). Create a new Bitmap the same size as the image control and associate it with it (set the Image property). Obtain a Graphics object for the Bitmap (Graphics.FromImage() I think). Clear() it with the background color (Color.White?).
Preload your three images on startup and write the code to toggle between them, selecting the "active one" every time a different button is selected. On the mouse down event, you can get the coordinates of the click easily. Use myGraphics.DrawImage(...) to draw the active image at that location onto the Bitmap. You can then save the Bitmap to a file or do whatever you want with it. All of these concepts have lots of examples, Google them.
If you want to interact with the images after you "drop" them (like move them around again or something), then you will need to maintain a data structure that tracks what and where you've dropped. A simple class that has a Point and Image reference will be sufficient. Each drop should add an entry to a List(Of ...) these objects. You'll probably then need to write code such as "which image is under the current mouse location?". This can be accomplished by iterating through the list and doing point/rectangle intersection testing.
Private Sub ToolStripSound_Click(sender As Object, e As EventArgs) Handles ToolStripSound.Click
If ToolStripSound.Checked = False Then
ToolStripSound.Checked = True
Else
ToolStripSound.Checked = False
End If
End Sub
Private Sub ToolStripSound_CheckedChanged(sender As Object, e As EventArgs) Handles ToolStripSound.CheckedChanged
' ToolStripSound.Checked = True
If ToolStripSound.Checked = True Then
Me.ToolStripSound.Image = Global.Traffic_Lights.My.Resources.Resources.Oxygen_Icons_org_Oxygen_Status_audio_volume_high
Else
Me.ToolStripSound.Image = Global.Traffic_Lights.My.Resources.Resources.Oxygen_Icons_org_Oxygen_Status_audio_volume_muted
End If
End Sub