In Listview assign each item (a folder) an image from with each folder - vb.net

I am developing an application to find, play and display all media, but primarily music. I am using Visual Studio 2012 in vb.net. On my form I have a Windows Media Player (WMP) and two listviews. The first listview (lvFolders) displays all folders of drive location. When I select a folder it automatically loads all files (media tracks) into the second listview (lvPlaylist), and starts playing the first track using the WMP. That all works well.
In each of these folders (500+) I have a cover of the respective album named "front.bmp". I cannot for the life of me work out what I am doing wrong. As the listview is populating the folders I am trying for it to load each image file located within that folder into the imagelist, and display the folders as large icons using that image. The result would be 500+ large folders each displaying their respective album cover from the imagelist.
I specifically didn't want to use Folder Browser Dialog or Open File Dialog. This application is for a touch based application for my own personal use.
I have attached my code in case it helps understand my dilemma.
Private Sub LoadFolders_Click(sender As Object, e As EventArgs) Handles btnLoadFolders.Click
For Each strDir As String In My.Computer.FileSystem.GetDirectories("E:\Music\TEST")
Dim imageListLarge As New ImageList()
Dim strAlbumArt As String = strDir & "\" & (My.Computer.FileSystem.GetName(strDir)) & ".bmp" 'URL of the image
imageListLarge.ColorDepth = ColorDepth.Depth32Bit 'Set the colour
imageListLarge.ImageSize = New Size(128, 128) 'Set image size
imageListLarge.Images.Add(strAlbumArt, Image.FromFile(strAlbumArt)) 'Add image to image list
lvFolders.LargeImageList = imageListLarge 'Assign the imagelist to the listview
Dim NewItem As New ListViewItem(My.Computer.FileSystem.GetName(strDir), strAlbumArt) 'Create Column 1 data
NewItem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(strDir).FullName) 'Create Column 2 data
lvFolders.Items.Add(NewItem) 'Load into listview
Next
End Sub

Dim strAlbumArt As String = strDir & "\" & (My.Computer.FileSystem.GetName(strDir)) & ".bmp"
doesn't have "front.bmp" in it. Are you sure you don't mean something like Dim strAlbumArt As String = strDir & "\front.bmp?

Related

How to display a single Windows Explorer folder (that cannot be navigated away from) within a userform?

I would like to have a box within the userform display the contents of a single folder.
I would like the folder to display icons similar to how Windows Explorer does, and I would also like users to be able to drag icons from other windows into it (just like a real explorer window).
I decided to use a listview, and this will populate it with a bunch of lines of text for each file, but clicking on them does nothing and I cannot drag anything in. Also they don't have icons.
Any ideas?
Dim fileEntries As String() = Directory.GetFiles("C:\Windows\")
For Each fileName As String In fileEntries
ListView1.Items.Add(fileName)
Next
This MSDN article describes exactly how to do this. it even gets the icons, as you requested! It also uses a ListView, too! Enjoy!
As Jeremy said, you will still need to hook up event, if you want it to respond to click (or drag) events.
Private listView1 As ListView
Private imageList1 As ImageList
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo("c:\")
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As System.IO.FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = SystemIcons.WinLogo
item = New ListViewItem(file.Name, 1)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub

Retrieving images from a database?

I'm new to the forums and wanted to ask a question that has been bugging me for ages. I am using Visual Studio express 2012 with Windows Forms.
I want to have a database consisting of different images. Each row has its own image, and the other fields in the row define the images characteristics (I.E. Colour = Red, Striped = Yes etc) and its own specific ID.
Now what I want to do is allow the user to search via the form (Selecting what characteristics they want the image to have based on options on the form and then using SQL statements to retrieve the images based on their inputs). The only issue I am having is displaying all of the images on the form when they have searched? Is there any idea as to how to do this dynamically?
I created a form with FlowLayoutPanel in it. I set its AutoScroll property to true so that if there more pictures than fit in the space, it'll show a scroll bar so you can see them all.
I'm not entirely sure how you're getting the image, but assuming you have a function that returns a list of images.
Private Function DoImageSearch(parameters As SearchParameters) As List(Of Image)
'Go get images from database
End Function
Then you could have a function like the following to dynamically create PictureBox controls to be added to the FlowLayoutPanel.
Private Sub DynamicallyCreatedPictureBoxes(images As List(Of Image))
For Each image In images
Dim picture = New PictureBox()
picture.Image = image
picture.Size = image.Size
FlowLayoutPanel1.Controls.Add(picture)
Next
End Sub
In this case I've set the size of the PictureBox to be the size of the image. You may want to try to scale them or make thumbnails, but I'll leave that up to you (or another question). You'd probably also want another method to clear the images.
Private Sub ClearPictureBoxes()
FlowLayoutPanel1.SuspendLayout()
For Each control As Control In FlowLayoutPanel1.Controls
control.Dispose()
Next
FlowLayoutPanel1.Controls.Clear()
FlowLayoutPanel1.ResumeLayout()
End Sub
I'm not confident that last method is entirely correct, but you'd probably want something close to it.
Try like the this,
If color_RadioButton.Checked = True and type_RadioButton.Checked = True Then
cmdTect="color='" & color_RadioButton.Text & "' and type='" & type_RadioButton.Text & "'"
ElseIf color_RadioButton.Checked = True and type_RadioButton.Checked = False Then
cmdTect="color='" & color_RadioButton.Text & "'"
ElseIf color_RadioButton.Checked = False and type_RadioButton.Checked = TrueThen
cmdTect="type='" & type_RadioButton.Text & "'"
End If
dim cmd as new sqlcommand("select count(photo) from tbl where " & cmdTect,conn)
dim cnt as integer=cmd.ExecuteScalar()
for i as integer=0 to cnt
cmd = New SqlCommand("select photo from tbl where" & cmdTect,conn)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Dim ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
Dim pic As New PictureBox
pic.BackgroundImage = Image.FromStream(ms, True)
Panel1.Controls.Add(pic)
End If
Next

How to make textfile to save in program directory in Visual Studio

As i have abandoned the array approach to the problem, i need to know how to make listbox to save in textfile always in program's directory so it can be used/accessed to populate a different listbox, any ideas? Below is my code.
SaveFileDialog1.Filter = "Text files (.txt)|.txt"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName <> "" Then
Using SW As New IO.StreamWriter(SaveFileDialog1.FileName, False)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End If
A little bit of research on your part would've helped you understand what you are trying to accomplish better.
How do I get Program Data directory? My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
How do I Write multiple lines to file? File.WriteAllLines()
How do I Read multiple lines from a file? File.ReadAllLines()
Once you understand the basics you can easily put them together
Create two List boxes, and one button on your WinForm:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.
'Get the Program Data Directory (This is hidden by default by the OS.)
Dim strPath As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Dim fileName As String = "myFile.txt"
Dim fullPath = Path.Combine(strPath, fileName)
Dim data As String() = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
'Save the items to ListBox1 First
For Each item As String In data
ListBox1.Items.Add(item)
Next
'Now write the items to the textfile, line by line.
File.WriteAllLines(fullPath, data)
'Read all lines we just saved and load them onto an array of strings.
Dim tempAllLines() As String = File.ReadAllLines(fullPath)
'Display each on ListBox2 by iterating the array.
For Each line As String In tempAllLines
ListBox2.Items.Add(line)
Next
End Sub
Here, I created this form so you can get an idea of what i'm referring to.
You can get the path to the current executable's folder like this:
folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
However, that will only work if the executable is a .NET assembly. Otherwise, you could use the first argument in the command line (which is the full executable file path), like this:
folderPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()(0))
If, on the other hand, you want to get the path of the current assembly (which may be different than the executable that loaded it) you could do this:
folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Or, if you want to just get the current directory, you could use this:
folderPath = Directory.GetCurrentDirectory()
Once you have the folder path, you can add the file name to it with Path.Combine, like this:
filePath = Path.Combine(folderPath, fileName)
However, it's not recommended that you write data directly to the program's running path, since the user may not have permission to write to that folder. Using the program data folder would certainly be better, but even that can be risky:
folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyAppName")
The recommended place to store data from .NET apps is Isolated Storage.

Restrict Image by selecting it's URL

I am trying to add Images from websites and I am facing poblem with an issue which is that when I am trying to go to google images and trying to add some Images and when I right click for some images I find "Copy Image URL" and for some I don't find it and I find "Copy link address".Now I want my users to restrict from adding the Images which contain "Copy Image URL"
And I am attaching Images so that you'll understand me in a better way.
How do I do that?
Here is the code for saving the image:
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = CType(pic.Image, Bitmap)
Dim filename As String = CStr(pic.Tag)
filename = filename.Substring(filename.LastIndexOf("/") + 1)
Dim ext As String = filename.Substring(filename.LastIndexOf("."))
'Here it gives me an error at(filename.lastindexof(".")
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()
'WEB CLIENT IS NEEDED TO DO THE DOWNLOAD
Dim MyWebClient As New System.Net.WebClient
'BYTE ARRAY HOLDS THE DATA
Dim ImageInBytes() As Byte = MyWebClient.DownloadData(url)
'CREATE A MEMORY STREAM USING THE BYTES
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
'CREATE A BITMAP FROM THE MEMORY STREAM
PictureBox1.Image = New System.Drawing.Bitmap(ImageStream)
In the top screenshot, you are right-clicking directly on an image.
In the bottom screenshot, you are right-clicking on an empty div with a z-index that puts it above the image.
Here's an example:
<a href="http://example.com">
<img src="myImg.jpg" style="position: absolute;" />
<div style="z-index:1; position:absolute; width:100%; height:100%;"></div>
</a>
When you mouse over the link in Google Images another div is shown on top that contains the saveable image. Have a look with Firebug and see for yourself :)
Note that there is no perfect way to prevent users from saving images from your website. You can disable right click, mask the image with a div, mask the image with a transparent image (so the user can right-click and save the image but they get the wrong one), prevent caching etc but ultimately any tech savvy user can get around this. Still, these approaches will stop casual users so it's better than nothing. If you want to find out more about the methods that I just named, I suggest Googling for "disable save image as" or "disable copy image url".
maybe helpful
Sub Base64Convert(ByVal Base64MSG As String)
'Setup image and get data stream together
Dim img As System.Drawing.Image
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
Dim b64 As String = Base64MSG
Dim b() As Byte
'Converts the base64 encoded msg to image data
b = Convert.FromBase64String(b64)
MS = New System.IO.MemoryStream(b)
'creates image
img = System.Drawing.Image.FromStream(MS)
'writes image for displaying
img.Save(Request.ServerVariables("APPL_PHYSICAL_PATH") & "LabelInfo.tiff", System.Drawing.Imaging.ImageFormat.Tiff)
'cleaning up house
img.Dispose()
MS.Close()
End Sub

VB.NET - Adding items to a listview as well as checkboxes and tag property

I've got this code which basically loops through a set of folders and subfolders and finds specific file types. And then lists these in a listview. Now, it's intended to list exe and msi files. And I've made it so that these icons can be doubleclicked after they have been listed. I do this by adding the path to the file in it's tag property.
But, my superiors want a checkbox next to each item. So that they can check each item they want installed. And then have a button which runs the path in each tag property one at a time. It's basically the part where I fill the listview with the checkbox, filename of the exe or msi file, tag and the icon that I'm wondering about.
This is the existing code. This includes just a Tile view of the listview.
Public Sub getDirectories(ByVal strFilepath As String, ByVal strFileExtension As String, ByVal objControl As Object)
'Load first files from the root folder. Then loop each subfolder
Dim di As New DirectoryInfo(strFilepath)
Dim aryFi As IO.FileInfo() = di.GetFiles(strFileExtension, SearchOption.AllDirectories)
Dim filePath As String
Dim fileIcon As Icon
' For each file in the root folder
For Each file In aryFi
If file.Extension = String.Empty Then
Else
filePath = GetAssociatedProgram(file.Extension)
On Error Resume Next
'Extract icon
fileIcon = Drawing.Icon.ExtractAssociatedIcon(filePath)
'Add the icon if we haven't got it already
objControl.StateImageList = Form1.iconList
If Form1.iconList.Images.ContainsKey(filePath) Then
Else
Form1.iconList.Images.Add(filePath, fileIcon)
End If
'Add item to list
objControl.items.add(file.Name, filePath).Tag = file.DirectoryName
End If
Next
End Sub
Basically I call this sub in this way:
getDirectories(strProgramLocation, "*.exe", Form1.listViewSupSoftware)
And I've found that I can add items to a listview which also contains columns:
Dim tempstr(2) As String
tempstr(0) = "Name of item"
tempstr(1) = "Target folder of item"
Dim tempNode As ListViewItem
tempNode = New ListViewItem(tempstr)
Form1.listViewItem.Items.Add(tempNode)
But there should be a way of combining these two right? I'm not sure how I can add a checkbox in the first column of the listview? I've already set the Checkbox property of the listview to True. But I could use some pointers here if anyone's got any. :)
Mmm, I don't understand quite well your question. If you already have the listbox you just need to use a CheckedListBox and loop thru all the checked items executing the executable stored into the tag property ...
As I said I'm not sure If I get what you mean ...