Get image location using a drag and drop - vb.net

I have a drag and drop event to get images into a picture box. I need to get the image location to string to store on my database. I can get the location if I use a OpenFileDialog, but if I use a drag and drop, I can't seem to get it. Here is my code:
Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter
'Procedure to copy the dragged picture from the
'open window
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
'If the file explorer is open, copy the picture to the box
e.Effect = DragDropEffects.Copy
picCategoryImage.BorderStyle = BorderStyle.FixedSingle
TextBox1.Text = picCategoryImage.ImageLocation
Else
'otherwise, don't take action
e.Effect = DragDropEffects.None
btnDeleteImage.Visible = False
End If
End Sub
Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop
'Procedure to select the pictue and drag to picturebox
Dim picbox As PictureBox = CType(sender, PictureBox)
Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
If files.Length <> 0 Then
Try
picbox.Image = Image.FromFile(files(0))
btnDeleteImage.Visible = True
picbox.BorderStyle = BorderStyle.None
picCategoryImage.BringToFront()
btnDeleteImage.BringToFront()
Catch ex As Exception
MessageBox.Show("Image did not load")
End Try
End If
End Sub

As suggested by Plutonix, you're already using the file path so you've already got it. That's how Image.FromFile is able to create an Image from a file. If you mean that you need to be able to get the path later then you have two main choices:
Do as you're doing and store the path in a member variable for later use.
Instead of calling Image.FromFile and setting the Image of the PictureBox, just call the Load method of the PictureBox. You can then get the path from the ImageLocation property.
I would actually suggest using option 2 regardless, because it has the added advantage of not locking the file the way your current code does.

Related

How to display icon in ListView in VB.Net

Can you help me to display icon view from the files i get from a directory
Here is my code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SearchDir("g:\")
End Sub
Public Sub SearchDir(ByVal sDir As String)
Dim fil As String
Try
For Each dir As String In Directory.GetDirectories(sDir)
For Each fil In Directory.GetFiles(dir, " *.doc ")
ListView1.Items.Add(fil)
Next
SearchDir(dir)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
this gives me a result, but in form of string displaying its path
First of all, you need to add ImageList tool from Visual Studio Toolbox. Then select its properties and select the images you need to work with.
After that, you need to use the corresponding given serial-wise IDs by ImageList in your ListView code as follows:
Declaration:
Private lView As ListViewItem ' listView's lView (not I-view)
lView = ListView1.Items.Add("Special iconic thing", 0) ' 0 = my icon ID in ImageList
You should get the similar to my output:
Hope it works for you.

Download Image under the Mouse pointer via WebBrowser

I'm navigating to Google Images using a WebBrowser control. The aim is to be able to right click on any image and download and populate a PictureBox background.
I have my own ContextMenuStrip with Copy on it and have disabled the built in context menu.
The issue I am having is that the coordinate returned from CurrentDocument.MouseMove are always relative to the first (top left) image.
So my code works correctly if the Image I want is the very first image on the page, however clicking on any other Images always returns the coordinates of the first image.
It would appear that the coordinates are relative to each Image rather than the page.
Private WithEvents CurrentDocument As HtmlDocument
Dim MousePoint As Point
Dim Ele As HtmlElement
Private Sub Google_covers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.IsWebBrowserContextMenuEnabled = False
WebBrowser1.ContextMenuStrip = ContextMenuStrip1
End Sub
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
CurrentDocument = WebBrowser1.Document
End Sub
Private Sub CurrentDocument_MouseMove(sender As Object, e As HtmlElementEventArgs) Handles CurrentDocument.MouseMove
MousePoint = New Point(e.MousePosition.X, e.MousePosition.Y)
Me.Text = e.MousePosition.X & " | " & e.MousePosition.Y
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
Ele = CurrentDocument.GetElementFromPoint(MousePoint)
If Ele.TagName = "IMG" Then
CopyToolStripMenuItem.Visible = True
Else
CopyToolStripMenuItem.Visible = False
End If
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click
Dim ToImg = Ele.GetAttribute("src")
mp3_row_edit.PictureBox1.BackgroundImage = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(ToImg)))
ToImg = Nothing
End Sub
This code allow to use a standard WebBrowser control to navigate to the Google Image search page and select/download an Image with a right-click of the Mouse.
To test it, drop a WebBrowser Control and a FlowLayoutPanel on a Form and navigate to a Google Image search page.
Things to know:
WebBrowser.DocumentCompleted: This event is raised each time one of the Sub-Documents inside a main HtmlDocument page is completed. Thus, it can be raised multiple times. We need to check whether the WebBrowser.ReadyState = WebBrowserReadyState.Complete.
Read these note about this: How to get an HtmlElement value inside Frames/IFrames?
The images in the Google search page can be inserted in the Document in 2 different manners: both using a Base64Encoded string and using the classic src=[URI] format. We need to be ready to get both.
The mouse click position can be espressed in either absolute or relative coordinates, referenced by the e.ClientMousePosition or e.OffsetMousePosition.
Read the notes about this feature here: Getting mouse click coordinates in a WebBrowser Document
The WebBrowser emulation mode can be important. We should use the most recent compatible mode available in the current machine.
Read this answer and apply the modifications needed to have the most recent Internet Explorer mode available: How can I get the WebBrowser control to show modern contents?.
Note that an event handler is wired up when the current Document is completed and is removed when the Browser navigates to another page. This prevents undesired calls to the DocumentCompleted event.
When the current Document is complete, clicking with the right button of the Mouse on an Image, creates a new PictureBox control that is added to a FlowLayouPanel for presentation.
The code in the Mouse click handler (Protected Sub OnHtmlDocumentClick()) detects whether the current image is a Base64Encoded string or an external source URI.
In the first case, it calls Convert.FromBase64String to convert the string into a Byte array, in the second case, it uses a WebClient class to download the Image as a Byte array.
In both cases, the array is then passed to another method (Private Function GetBitmapFromByteArray()) that returns an Image from the array, using Image.FromStream() and a MemoryStream initialized with the Byte array.
The code here is not performing null checks and similar fail-proof tests. It ought to, that's up to you.
Public Class frmBrowser
Private WebBrowserDocumentEventSet As Boolean = False
Private base64Pattern As String = "base64,"
Private Sub frmBrowser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.IsWebBrowserContextMenuEnabled = False
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete AndAlso WebBrowserDocumentEventSet = False Then
WebBrowserDocumentEventSet = True
AddHandler WebBrowser1.Document.MouseDown, AddressOf OnHtmlDocumentClick
End If
End Sub
Protected Sub OnHtmlDocumentClick(sender As Object, e As HtmlElementEventArgs)
Dim currentImage As Image = Nothing
If Not (e.MouseButtonsPressed = MouseButtons.Right) Then Return
Dim source As String = WebBrowser1.Document.GetElementFromPoint(e.ClientMousePosition).GetAttribute("src")
If source.Contains(base64Pattern) Then
Dim base64 As String = source.Substring(source.IndexOf(base64Pattern) + base64Pattern.Length)
currentImage = GetBitmapFromByteArray(Convert.FromBase64String(base64))
Else
Using wc As WebClient = New WebClient()
currentImage = GetBitmapFromByteArray(wc.DownloadData(source))
End Using
End If
Dim p As PictureBox = New PictureBox() With {
.Image = currentImage,
.Height = Math.Min(FlowLayoutPanel1.ClientRectangle.Height, FlowLayoutPanel1.ClientRectangle.Width)
.Width = .Height,
.SizeMode = PictureBoxSizeMode.Zoom
}
FlowLayoutPanel1.Controls.Add(p)
End Sub
Private Sub WebBrowser1_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
If WebBrowser1.Document IsNot Nothing Then
RemoveHandler WebBrowser1.Document.MouseDown, AddressOf OnHtmlDocumentClick
WebBrowserDocumentEventSet = False
End If
End Sub
Private Function GetBitmapFromByteArray(imageBytes As Byte()) As Image
Using ms As MemoryStream = New MemoryStream(imageBytes)
Return DirectCast(Image.FromStream(ms).Clone(), Image)
End Using
End Function
End Class

How change image in generated imagebox vb

I have to do a program where I can generate Button, Label, ImageBox and work with them. Now I am searching how change image in created ImageBox, it writes: this element doesn't exist. How can I get access to the created elements?
Dim PictureB As New PictureBox
PictureB.Size = New System.Drawing.Size(200, 120)
PictureB.Location = New System.Drawing.Point(350, 20)
PictureB.BorderStyle = BorderStyle.Fixed3D
TabPage1.Controls.Add(PictureB)
"New sub"
OpenFileDialog1.ShowDialog()
PictureB.ImageLocation = OpenFileDialog1.FileName
PictureB is not accessible in your "new sub" because it only exists in the subprocedure that you created it in as a temporary, private variable. The PictureBox, however, that you created, does exist in TabPage1.Controls, so you can access it in a loop.
Based on your requirements, it seems that you also need to get the exact PictureBox that you created, so I would suggest adding a Name to it when you create it, something like PictureB.Name = "Pic1". I have included a sample Sub below that shows how you might accomplish your goal.
Public Sub SetImage(ByVal PictureBoxName As String)
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each c As Control In TabPage1.Controls
Dim pb As PictureBox = TryCast(c, PictureBox)
If Not IsNothing(pb) Then
If pb.Name = PictureBoxName Then
pb.ImageLocation = OpenFileDialog1.FileName
Exit For
End If
End If
Next
End If
End Sub
Alternatively, you could look into creating event handles instead: that would be more involved, but would be a good learning experience.

How To Save/Recall Folderbrowserdialog SelectedPath

I'm currently teaching myself (with the help of SO & Google) VB.Net to create a launcher for a multiplayer mod and I need users upon first launch of my application to input where their folder is stored, so far I have;
Dim folderDlg As System.Windows.Forms.FolderBrowserDialog
folderDlg = New System.Windows.Forms.FolderBrowserDialog
folderDlg.Description = "Please select your multiplayer folder"
If My.Settings.isFirstRun Then
My.Settings.isFirstRun = False
My.Settings.Save()
folderDlg.ShowDialog()
Else
End If
The button to run the mod itself
Private Sub Launch_mp_Click(sender As Object, e As EventArgs) Handles Launch_mp.Click
If My.Computer.FileSystem.FileExists("launcher.exe") Then
Process.Start("launcher.exe")
Timer2.Interval = 1000
Timer2.Start()
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
p = Process.GetProcessesByName("eurotrucks2")
If p.Count > 0 Then
Timer2.Stop()
Me.WindowState = FormWindowState.Minimized
Me.Visible = True
Else
End If
End Sub
I'm confused as to how I can store the users selected path and then recall it later on for the button without always asking for the dir.
You are almost there:
You have various options where to store the information: registry, old-style using ini-files or in the config file of your application. I would suggest using the config file since you already store the isFirstRun-varialbe in the config. In project explrorer look at the "My Project" folder and double click an item called "Settings". Add a setting of type string called "ModFolder". After that you will be able to access the value of that setting using My.Settings.ModFolder varialbe (see here).
Use the FolderBrowserDialog to store the folder (see here)
if folderDlg.ShowDialog() = DialogResult.Ok then
My.Settings.ModFoler = folderDlg.SelectedPath
My.Settings.Save
end if
When your application starts next time the ModFolder-variable will automaticall hold the value stored so instead of If My.Settings.isFirstRun Then I would check:
If File.Exists(Path.Combine(My.Settings.ModFolder, "AppToStart.Exe")) then
...
end if
If the file exists launch it, if not re-show the dialog to pick the folder.

Add event to dynamically created button

I have 4 picture boxes on my form. Whenever a new picture is selected the next available box populated and a button is created within that picture box. I would like that button to be able to delete the image within that particular picturebox. I know how to create an event handler and then add the address to the button, what I do not know how to do is how to write the code so as to actually delete the assigned image on the assigned box. Here is my code to load the pictures and create the button:
Private Sub btnAddImage_Click(sender As Object, e As EventArgs) Handles btnAddImage.Click, btnUploadImage.Click 4
Dim btn As Button = New Button
btn.Text = "Remove Image"
'Procedure places the pictures in each empty picturebox in sequence
ofdBrowsePictures.Multiselect = False
ofdBrowsePictures.Title = "Select Image to Upload"
ofdBrowsePictures.Filter = "Image Files |*.jpg*"
If ofdBrowsePictures.ShowDialog() = Windows.Forms.DialogResult.OK Then
'create array of each picture box and check if they are empty
'Check if the picturebox contains a tag with the image path
Dim PBs() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
Dim nextPB = PBs.Where(Function(x) IsNothing(x.Image)).FirstOrDefault
If Not IsNothing(nextPB) Then
'if the box does not contain a image path, then place the picture on that box
nextPB.ImageLocation = ofdBrowsePictures.FileName
nextPB.Tag = nextPB.ImageLocation.ToString
'add a button
nextPB.Controls.Add(btn)
'Create a border style on the image
nextPB.BorderStyle = BorderStyle.FixedSingle
End If
End If
End Sub
what I do not know how to do is how to write the code so as to actually delete the assigned image on the assigned box
I assume "delete image" means remove from the picture box, not delete from disk.
' what is 4???
Private Sub btnAddImage_Click(sender As Object,
e As EventArgs) Handles btnAddImage.Click, btnUploadImage.Click 4
Dim btn As Button = New Button
btn.Text = "Remove Image"
' bla bla bla set the imagelocation
AddHandler btn.Click, AddressOf RemoveImage_Click
pb1.Controls.Add(btn) ' btn.parent = this pb
End Sub
Private Sub RemoveImage_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim btn As Button = CType(sender, Button)
' clear image
CType(btn.Parent, PictureBox).ImageLocation = ""
RemoveHandler btn.Click, AddressOf RemoveImage_Click
' remove the control
pb1.Controls.Remove(btn)
' if you remove a control, dispose of it
btn.Dispose()
End Sub
I am not sure I would invoke the dialog before checking for the next PB (nor would I create the new Button), since you seem to want to do nothing if there is no nextPB to play with.
For more information about Disposing of controls you Remove, see:
Memory Leak
What are Parking Windows
Adding / removing controls
Basically, forms dispose of controls when you close them. If you Remove a control, the form no longer has a reference and cannot. As a result, you should be disposing them.
Either of these clear a picturebox image set with ImageLocation:
PictureBox1.Image = Nothing
PictureBox1.ImageLocation = ""
PictureBox1.ImageLocation = String.Empty