Getting duplicate entries in treeView and Extra Space in listView Item image - vb.net

I am making a test program to let the user select a folder from a tree view which will show the drives and folders (when expanded) and the files that are present in the selected folder will be displayed in the listview.
The problem i am facing with the listview is that, there is a extra space added before the file icon of every file.
And i am also getting duplicate folder entries when expanded in the treeview.
the icon size of imageListListView is 24x24
Public Class FolderTreeStructure
Private Sub FolderTreeStructre_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'add drive list in treeview
Dim drives() As String = System.IO.Directory.GetLogicalDrives()
For Each drive In drives
TreeView1.Nodes.Add(drive)
Next
'add folder present in each drives
Dim folders() As String
Dim j As Integer = 0
For i As Integer = 0 To TreeView1.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(TreeView1.Nodes.Item(i).Text)
For Each folder In folders
TreeView1.Nodes.Item(i).Nodes.Add(folder)
TreeView1.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
End Sub
Private Sub TreeView1_AfterExpand(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterExpand
Me.Cursor = Cursors.WaitCursor
Dim folders() As String
Dim j As Integer = 0
TreeView1.BeginUpdate()
For i As Integer = 0 To e.Node.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(e.Node.Nodes.Item(i).Text)
For Each folder In folders
e.Node.Nodes.Item(i).Nodes.Add(folder)
e.Node.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
TreeView1.EndUpdate()
Me.Cursor = Cursors.Default
End Sub
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
addFolderItems(e.Node.Text)
End Sub
Public Sub addFolderItems(ByVal path As String)
Try
ListView1.Items.Clear()
Dim files() As String = IO.Directory.GetFiles(path)
Dim fileCount As Integer = files.Length
Dim fileInfo As IO.FileInfo
Dim i As Integer = 0
Dim Items = ListView1.Items
'different file sizes
Dim fileSize As Long
Dim kb As Double
Dim mb As Double
Dim gb As Double
'for extracting file type description
Dim Clskey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
Dim ExtKey As Microsoft.Win32.RegistryKey
Dim Appkey2 As Microsoft.Win32.RegistryKey
Dim AppDesc As String
'to hold file icon
Dim iconForFile As Icon = SystemIcons.WinLogo
ListView1.BeginUpdate()
For Each file In files
Try
fileInfo = New IO.FileInfo(file)
'adds item number
Items.Add(Items.Count + 1)
'adds file name
Items.Item(i).SubItems.Add(fileInfo.Name)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (ImageListListView.Images.ContainsKey(fileInfo.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
ImageListListView.Images.Add(fileInfo.Extension, iconForFile)
End If
Items.Item(i).ImageKey = fileInfo.Extension
'adds file size
fileSize = fileInfo.Length
If fileSize > 1024 Then
kb = fileSize / 1024
If kb > 1024 Then
mb = kb / 1024
If mb > 1024 Then
gb = mb / 1024
Items.Item(i).SubItems.Add(Format(gb, "0.00") & " GB")
Else
Items.Item(i).SubItems.Add(Format(mb, "0.00") & " MB")
End If
Else
Items.Item(i).SubItems.Add(Format(kb, "0.00") & " KB")
End If
Else
Items.Item(i).SubItems.Add(fileSize.ToString & " bytes")
End If
'adds file extension without .
If fileInfo.Extension.Length > 0 Then
Items.Item(i).SubItems.Add(fileInfo.Extension.Substring(1))
Else
Items.Item(i).SubItems.Add(fileInfo.Extension)
End If
'adds date modified
Items.Item(i).SubItems.Add(fileInfo.LastWriteTime.ToString)
'extract file type description from registry
ExtKey = Clskey.OpenSubKey(fileInfo.Extension, False)
If ExtKey IsNot Nothing Then 'Occurs nullreff when extension not found
AppDesc = ExtKey.GetValue("", "")
Appkey2 = Clskey.OpenSubKey(AppDesc)
Items.Item(i).SubItems.Add(Appkey2.GetValue("", ""))
End If
i += 1
Catch
Continue For
End Try
Next
ListView1.EndUpdate()
Catch e As Exception
MsgBox(e.ToString)
End Try
End Sub
End Class
Link for image
http://i.imgur.com/GLS0ZiO.png

Related

How to operate with binary files faster?

What I'm trying to do:
Open two binary files, each 64 MB
Take first half of each byte of each file and combine those halves in 1 bytes same with second half, for example: first byte in first file is 0x51, in second file its 0xA2, so I need write two bytes in third file which are 0x5A and 0x12, same for whole bytes, therefore final length in third file will be 128 MB.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Try
' choosing first file
OpenFileDialog1.FileName = "First file"
OpenFileDialog1.Title = "Choose the Address.bin file"
OpenFileDialog1.Filter = "bin files (*.bin)|*.bin|All files
(*.*)|*.*"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK
Then
Label1.Text =
System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
Else
Exit Sub
End If
Catch ex As Exception
End Try
Try ' choosing first file
OpenFileDialog1.FileName = "Second FIle"
OpenFileDialog1.Title = "Choose the Flash.bin file"
OpenFileDialog1.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Label2.Text = System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
Else
Exit Sub
End If
Catch ex As Exception
End Try
Dim firstFileByte(1) As Byte
Dim SecondFileByte(1) As Byte
Dim Result As String
Dim Result2 As String
Dim Final(1) As Byte
For i = 0 To FileLen(Label1.Text) - 1
Using FirstFile As New FileStream(Label1.Text, FileMode.Open) 'save
'FIRST DIGIT********************************************************************************************
FirstFile.Seek(i, SeekOrigin.Begin)
FirstFile.Read(firstFileByte, 0, 1)
'TextBox1.Text = final(0).ToString("X")
Using SecFile As New FileStream(Label2.Text, FileMode.Open) 'save
SecFile.Seek(i, SeekOrigin.Begin)
SecFile.Read(SecondFileByte, 0, 1)
End Using
Result = firstFileByte(0).ToString("X2").Substring(0, 1) & SecondFileByte(0).ToString("X2").Substring(0, 1) ' comobining frist half of the first file and second file
Result2 = firstFileByte(0).ToString("X2").Substring(1, 1) & SecondFileByte(0).ToString("X2").Substring(1, 1) ' comobining second half of the first file and second file
End Using
Using vFs As New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Result.bin", FileMode.Append) ' save
TextBox1.Text = Result2
'Dim FileLenVar As UInt32 = FileLen(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Result.bin") - 1
Final(0) = Convert.ToByte(Result, 16) 'converting result to the byte
Final(1) = Convert.ToByte(Result2, 16)
vFs.Write(Final, 0, 1)
vFs.Write(Final, 1, 1)
End Using
Next
End Sub
It works, but takes a lot of time: it writes 1 MB in 1 minute. How can I optimize it?
The files are small enough to load into RAM for processing. Processing the data in RAM can minimise the disk I/O needed, the latter very often being the slowest part of a program, especially if it is done in very small pieces like individual bytes. As also noted by Ben Voigt, string operations are somewhat slower than numeric operations.
Here's a simple demonstration of what could be done:
Imports System.IO
Module Module1
Dim f1 As String = "C:\temp\A.bin"
Dim f2 As String = "C:\temp\B.bin"
Dim outFile As String = "C:\temp\C.bin"
Sub CombineFiles()
Dim a1 = File.ReadAllBytes(f1)
Dim a2 = File.ReadAllBytes(f2)
Dim c(a1.Length + a2.Length - 1) As Byte ' c for combined
Dim highBits As Byte = &HF0
Dim lowBits As Byte = &HF
For i = 0 To c.Length - 1 Step 2
c(i) = a1(i \ 2) And highBits Or a2(i \ 2) >> 4
c(i + 1) = a1(i \ 2) << 4 Or a2(i \ 2) And lowBits
Next
File.WriteAllBytes(outFile, c)
End Sub
Sub CreateTestFiles()
'TODO: be more creative with the generated data.
Dim nBytes = 64
Dim a(nBytes - 1) As Byte
For i = 0 To nBytes - 1
a(i) = &H12
Next
File.WriteAllBytes(f1, a)
For i = 0 To nBytes - 1
a(i) = &HAB
Next
File.WriteAllBytes(f2, a)
End Sub
Sub Main()
'CreateTestFiles()
CombineFiles()
End Sub
End Module
Of course, you'd check that the input files were of equal length, and check for any other possible problems ;)

Item pairing between two .txt

I have been trying to combine or pair two text files.
One file contains User:Key
The other file contains Key:Pass
I want a 3rd text file created containing the corresponding pairs of User:Pass based on the key matching.
Here is what Ive tried most recently
Private Sub Rotate()
Dim Cracked() As String = IO.File.ReadAllLines(TextBox1.Text)
For Each lineA In Cracked
TextBox5.Text = lineA
check()
Next
End Sub
Private Sub check()
Dim toCheck() As String = TextBox5.Text.Split(":")
Dim tHash As String = toCheck(0)
Dim tPass As String = toCheck(1)
Dim lines1() As String = IO.File.ReadAllLines(TextBox2.Text)
For Each line In lines1
If lines1.Contains(tHash) Then
Dim toAdd() As String = line.Split(":")
Dim uHash As String = toCheck(0)
Dim uUser As String = toCheck(1)
ListBox1.Items.Add(uUser + ":" + tPass)
End If
Next
End Sub
Public Sub CopyListBoxToClipboard(ByVal ListBox2 As ListBox)
Dim buffer As New StringBuilder
For i As Integer = 0 To ListBox1.Items.Count - 1
buffer.Append(ListBox1.Items(i).ToString)
buffer.Append(vbCrLf)
Next
My.Computer.Clipboard.SetText(buffer.ToString)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
CopyListBoxToClipboard(ListBox1)
End Sub
The delimiter changes but for now the : works.
I tried splitting and matching but either the textbox5 does not rotate or it rotates through the list and thats all.
Something like this?
Dim KeyPassFile As String = "..."
Dim UserKeyFile As String = "..."
Dim UserPassFile As String = "..."
Dim KeyPass As New Hashtable
' Read Key:Pass file
For Each Line In IO.File.ReadAllLines(KeyPassFile)
Dim iStart = Line.IndexOf(":")
Dim Key = Line.Substring(0, iStart)
Dim Pass = Line.Substring(iStart + 1)
KeyPass.Add(Key, Pass)
Next
' Create User:Pass file
Dim OutFile = IO.File.CreateText(UserPassFile)
' Read User:Key file
For Each Line In IO.File.ReadAllLines(UserKeyFile)
Dim iStart = Line.IndexOf(":")
Dim User = Line.Substring(0, iStart)
Dim Key = Line.Substring(iStart + 1)
If KeyPass.ContainsKey(Key) Then
' We have a match for the key, write it to the file
OutFile.WriteLine(User & ":" & KeyPass(Key))
End If
Next
OutFile.Close()
This will probably not work for very large files that doesn't fit in memory, and there is no duplicate check for the key insertion in the hashtable, but I'll leave something for you to do.. :)
Also, in your code, you read the file specified in the TextBox2.Text as many times as there are lines in the TextBox1.Text file..

Get the size of a Sub Folder/Sub Directory excluding the Parent Folder

i have a listview that shows folders and files, and i can display the size of the files and subfolders, but how do i do it with subfolders only not including the parent/root folder.
EDIT
like, if Folder1's size is 10 MB and it has a SubFolder with 20 MB size with a total of 30 MB, it should only get the size of the SubFolder which is 20 MB when displaying the contents of the Folder1 in a ListView.
Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
Dim Size As Long = 0
Dim dis As DirectoryInfo() = d.GetDirectories()
Dim di As DirectoryInfo
For Each di In dis
Size += DirSize(di)
Next di
Return Size
End Function
my listview code:
Sub lv1items()
ListView1.Items.Clear()
Dim fPath As String = Form2.TextBox1.Text
Dim di = New DirectoryInfo(fPath)
' store imagelist index for known/found file types
Dim exts As New Dictionary(Of String, Int32)
If di.Exists = False Then
MessageBox.Show("Destination path" & " " & Form2.TextBox1.Text & " is not found.", "Directory Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form2.Show()
Else
Dim img As Image
Dim lvi As ListViewItem
For Each d In di.EnumerateDirectories("*.*", SearchOption.TopDirectoryOnly)
lvi = New ListViewItem(d.Name)
lvi.SubItems.Add(DirSize(di).ToString("0.00") & " MB")
lvi.SubItems.Add(d.CreationTime.Date)
ListView1.Items.Add(lvi)
img = NativeMethods.GetShellIcon(d.FullName)
ImageList1.Images.Add(img)
lvi.ImageIndex = ImageList1.Images.Count - 1
Next
End Sub
it returns a 0 size folder, but it has a file inside.
a little help please?
You can use this function:
Public Function GetDirectorySize(path As String) As Long
Dim files() As String = Directory.GetFiles(path, "*", SearchOption.AllDirectories)
Dim size As Long = 0
For Each file As String In files
Dim info As New FileInfo(file)
size += info.Length
Next
Return size
End Function
Note that this checks the size of every file in the folder and its subdirectories. Thus it is guaranteed to return the correct size.
Proof that it works:
Root:
SubFolder:
Total Size = (1483 + 25315) * 1024 = 274411152 bytes.
Program Output:
27440016 bytes ≈ 274411152 bytes.
Note: The difference exists because Windows Explorer rounds off some bytes to display the KB. If you view the properties of each file and add up then you will get the same size from both Explorer and the function.

Use streamreader to load data from text file into textboxes, code cannot find objStudent array

Option Strict On
Imports System.Text.RegularExpressions
Imports System.IO
Public Class StudentTestScores
Private Structure Student
Dim strStudentName As String
Dim dblTestScores() As Double
Dim dblAverage As Double
End Structure
Public Function GetDoubleTestScore(ByVal value As String) As Double
'Checks if the value is numeric and returns message if error is found
If IsNumeric(value) Then
Dim dblValue = CDbl(value)
'Check to make sure number is a positive and less or equal to 100
If dblValue >= 0 And dblValue <= 100 Then
Return dblValue
Else
Throw New Exception("The number needs to be between 0 and 100")
End If
Else
Throw New Exception("Please enter a number in the test score area.")
End If
End Function
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
'Creates variable and runs isValidName
Dim objStudent(6) As Student
If isValidName() = True Then
Try
' This initializes each of the test score arrays in a Student object
For i As Integer = 0 To 5
InitializeTestScores(objStudent(i))
Next
InitializeTestScores(objStudent(0))
'runs isNumeric function to txtStudentScores
objStudent(0).dblTestScores(0) = GetDoubleTestScore(txtStudent1Score1.Text)
objStudent(0).dblTestScores(1) = GetDoubleTestScore(txtStudent1Score2.Text)
objStudent(0).dblTestScores(2) = GetDoubleTestScore(txtStudent1Score3.Text)
objStudent(0).dblTestScores(3) = GetDoubleTestScore(txtStudent1Score4.Text)
objStudent(0).dblTestScores(4) = GetDoubleTestScore(txtStudent1Score5.Text)
objStudent(1).dblTestScores(0) = GetDoubleTestScore(txtStudent2Score1.Text)
objStudent(1).dblTestScores(1) = GetDoubleTestScore(txtStudent2Score2.Text)
objStudent(1).dblTestScores(2) = GetDoubleTestScore(txtStudent2Score3.Text)
objStudent(1).dblTestScores(3) = GetDoubleTestScore(txtStudent2Score4.Text)
objStudent(1).dblTestScores(4) = GetDoubleTestScore(txtStudent2Score5.Text)
objStudent(2).dblTestScores(0) = GetDoubleTestScore(txtStudent3Score1.Text)
objStudent(2).dblTestScores(1) = GetDoubleTestScore(txtStudent3Score2.Text)
objStudent(2).dblTestScores(2) = GetDoubleTestScore(txtStudent3Score3.Text)
objStudent(2).dblTestScores(3) = GetDoubleTestScore(txtStudent3Score4.Text)
objStudent(2).dblTestScores(4) = GetDoubleTestScore(txtStudent3Score5.Text)
objStudent(3).dblTestScores(0) = GetDoubleTestScore(txtStudent4Score1.Text)
objStudent(3).dblTestScores(1) = GetDoubleTestScore(txtStudent4Score2.Text)
objStudent(3).dblTestScores(2) = GetDoubleTestScore(txtStudent4Score3.Text)
objStudent(3).dblTestScores(3) = GetDoubleTestScore(txtStudent4Score4.Text)
objStudent(3).dblTestScores(4) = GetDoubleTestScore(txtStudent4Score5.Text)
objStudent(4).dblTestScores(0) = GetDoubleTestScore(txtStudent5Score1.Text)
objStudent(4).dblTestScores(1) = GetDoubleTestScore(txtStudent5Score2.Text)
objStudent(4).dblTestScores(2) = GetDoubleTestScore(txtStudent5Score3.Text)
objStudent(4).dblTestScores(3) = GetDoubleTestScore(txtStudent5Score4.Text)
objStudent(4).dblTestScores(4) = GetDoubleTestScore(txtStudent5Score5.Text)
objStudent(5).dblTestScores(0) = GetDoubleTestScore(txtStudent6Score1.Text)
objStudent(5).dblTestScores(1) = GetDoubleTestScore(txtStudent6Score2.Text)
objStudent(5).dblTestScores(2) = GetDoubleTestScore(txtStudent6Score3.Text)
objStudent(5).dblTestScores(3) = GetDoubleTestScore(txtStudent6Score4.Text)
objStudent(5).dblTestScores(4) = GetDoubleTestScore(txtStudent6Score5.Text)
' This loops through each Student structure object and calculates the average test score.
For i As Integer = 0 To 5
objStudent(i).dblAverage = CaculateStudentAverage(objStudent(i))
Next
objStudent(0).strStudentName = txtStudent1.Text
objStudent(1).strStudentName = txtStudent2.Text
objStudent(2).strStudentName = txtStudent3.Text
objStudent(3).strStudentName = txtStudent4.Text
objStudent(4).strStudentName = txtStudent5.Text
objStudent(5).strStudentName = txtStudent6.Text
lblAverageStudent1.Text = objStudent(0).dblAverage.ToString()
lblAverageStudent2.Text = objStudent(1).dblAverage.ToString()
lblAverageStudent3.Text = objStudent(2).dblAverage.ToString()
lblAverageStudent4.Text = objStudent(3).dblAverage.ToString()
lblAverageStudent5.Text = objStudent(4).dblAverage.ToString()
lblAverageStudent6.Text = objStudent(5).dblAverage.ToString()
'This creates the text file the program will write to
Dim StudentFile As System.IO.StreamWriter
Dim strFileName As String = "StudentTestScore.txt"
StudentFile = System.IO.File.AppendText(strFileName)
'Creates for loop that takes the 6 students
For i As Integer = 0 To 5
StudentFile.Write("Student Name: ")
StudentFile.Write(objStudent(i).strStudentName)
StudentFile.Write(" Student Test Scores: ")
'This creates a loop for the students and test scores
For intIndex2 As Integer = 0 To 4
StudentFile.Write(objStudent(i).dblTestScores(intIndex2).ToString())
If intIndex2 <> 4 Then
StudentFile.Write(", ")
End If
'Finally the average is ran using the objStudent (i)
Next
StudentFile.Write(" Average Score = ")
StudentFile.Write(objStudent(i).dblAverage.ToString())
StudentFile.WriteLine()
Next
'Closes the text file that was created
StudentFile.Close()
'Shows a message box that says the file was written to the text file and or modified
MessageBox.Show("Student Test Score file was created or modified.")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
End Sub
Private Sub InitializeTestScores(ByRef objStudent As Student) 'references objStudent object
' This takes the array dblTestScores and makes it a fixed array of size 6 since it could not be given a number in the structure
ReDim objStudent.dblTestScores(5)
End Sub
Private Function CaculateStudentAverage(ByVal objStudent As Student) As Double
' This loop loops through each value in dblTestScores and then just adds them to objstudent
For i As Integer = 0 To 4
objStudent.dblAverage += objStudent.dblTestScores(i)
Next
' This divides and then stores it back into the variable
objStudent.dblAverage /= 5
'Returns student average
Return objStudent.dblAverage
End Function
Private Sub LoadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadToolStripMenuItem.Click
' Create a new open file dialog
Dim MyFileDialog As New System.Windows.Forms.OpenFileDialog
' Configure the dialog to show only text files
' Set its title and set the filename field blank for the moment.
MyFileDialog.FileName = "StudentTestScore.txt"
' Show the dialog and see if the user pressed ok.
If MyFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Check to see if they selected a file and that it exists.
If File.Exists(MyFileDialog.FileName) Then
Dim strFile As String = MyFileDialog.FileName
Dim reader As StreamReader
Try
' Setup a file stream reader to read the text file.
reader = New StreamReader(New FileStream(strFile, FileMode.Open, FileAccess.Read))
' While there is data to be read, read each line into a rich edit box control.
Select
Case 0
txtStudent1.Text = Student.objStudent(0)
txtStudent1Score1.Text =
End Select
While reader.Peek > -1
txtStudent1.Text &= reader.ReadLine()
End While
' Close the file
reader.Close()
Catch ex As FileNotFoundException
' If the file was not found, tell the user.
MessageBox.Show("File was not found. Please try again.")
End Try
End If
End If
End Sub
End Class

Opening and closing multiple forms from a main form in VB.net

In my project (kind of a screen saver) I have a main form and second form (PicView).
I want to open many instances of the second form and display a picture in it.
I can do that fine, but when I have opened e.g. 4 forms I would like to close the first before opening the next one so that the total number of forms stays at 4.
The problem I have is that the closing routine does not know about the form instances and the debugger tells me to create a new instance, but I would like to use the existing ones.
How can I make the form names visible to the main routine or do I need to pass reference to the created forms?
Thanks
Private Sub btnTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
gsPic1 = "D:\My Stuff\411CANON\IMG_1161.JPG"
gsPic2 = "D:\My Stuff\411CANON\IMG_1167.JPG"
gsPic3 = "D:\My Stuff\411CANON\IMG_1174.JPG"
gsPic4 = "D:\My Stuff\411CANON\IMG_1178.JPG"
ScreenSavePicIndex(gsPic1, 1)
Application.DoEvents()
ScreenSavePicIndex(gsPic2, 2)
Application.DoEvents()
ScreenSavePicIndex(gsPic3, 3)
Application.DoEvents()
ScreenSavePicIndex(gsPic4, 4)
MsgBox("Now Closing 1")
CloseScreenSaverPic(1)
Application.DoEvents()
MsgBox("Now Closing 3")
CloseScreenSaverPic(3)
Application.DoEvents()
MsgBox("Now Closing 4")
CloseScreenSaverPic(4)
Application.DoEvents()
End Sub
Private Sub CloseScreenSaverPic(ByVal iIndex As Integer)
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
frmPicViewerScrSav(iIndex).Close()
End Sub
Private Sub ScreenSavePicIndex(ByVal sFilePathandName As String, iIndex As Integer)
Dim iTargetHeight As Integer
Dim iTargetWidth As Integer
Dim dFactorHeight As Double
Dim dFactorWidth As Double
Dim objImage As System.Drawing.Image
Try
objImage = System.Drawing.Image.FromFile(sFilePathandName)
Catch ex As Exception
objImage = Nothing
End Try
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
Dim dFactor As Double
dFactor = 1
frmPicViewerScrSav(iIndex).FormBorderStyle = Windows.Forms.FormBorderStyle.None
iTargetWidth = Screen.PrimaryScreen.Bounds.Width / giScreenSavePicSize
iTargetHeight = Screen.PrimaryScreen.Bounds.Height / giScreenSavePicSize
'Check if the pic is bigger than what we want to display
If objImage.Width > iTargetWidth Then
'if it is wider then we need to find out how much bigger it is by factor
dFactorWidth = iTargetWidth / objImage.Width
End If
If objImage.Height > iTargetHeight Then
'if it is higher then we need to find out how much bigger it is by factor
dFactorHeight = iTargetHeight / objImage.Height
End If
If dFactorWidth > dFactorHeight Then
dFactor = dFactorWidth
Else
dFactor = dFactorHeight
End If
'Console.WriteLine("Factor is: " & dFactor)
frmPicViewerScrSav(iIndex).Width = objImage.Width * dFactor
frmPicViewerScrSav(iIndex).Height = objImage.Height * dFactor
objImage.Dispose()
Dim r As New Random()
Dim x As Integer = r.Next(Screen.PrimaryScreen.Bounds.Width - frmPicViewerScrSav(iIndex).Width)
Dim y As Integer = r.Next(Screen.PrimaryScreen.Bounds.Height - frmPicViewerScrSav(iIndex).Height)
Dim p As New Point(x, y)
'Console.WriteLine("Putting it at x= " & x & ", y= " & y)
frmPicViewerScrSav(iIndex).Location = p
frmPicViewerScrSav(iIndex).PictureBox1.Hide()
frmPicViewerScrSav(iIndex).PictureBox1.ImageLocation = sFilePathandName
frmPicViewerScrSav(iIndex).PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
frmPicViewerScrSav(iIndex).PictureBox1.Show()
frmPicViewerScrSav(iIndex).Show()
End Sub