How can I close the PrintPreviewDialog once the printing is complete? - vb.net

As a new programmer in VB, I struggled to get my print routine working. Searching through a number of sources I developed the hybrid below which is working to print a simple .txt file. My question sounds like a simple one but I've learned nothing is simple in printing. How do I get the PrintPreviewDialog to close once the printing is complete?
Private Sub BtnPrint_Click(sender As Object, e As EventArgs) Handles BtnPrint.Click
Try
PrintPreviewDialog1.Document = PrintDocument1
PageSetupDialog1.PageSettings =
PrintDocument1.DefaultPageSettings
If PageSetupDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDocument1.DefaultPageSettings =
PageSetupDialog1.PageSettings
PrintPreviewDialog1.Size = New System.Drawing.Size(500, 600)
PrintPreviewDialog1.ShowDialog()
End If
Catch ex As Exception
MessageBox.Show("Printing Operation Failed" & vbCrLf &
ex.Message)
End Try
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Static MyNewAcctFile As String = IO.File.ReadAllText(strErrorFile)
Dim printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(MyNewAcctFile, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(MyNewAcctFile, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
MyNewAcctFile = MyNewAcctFile.Substring(charsFitted)
If MyNewAcctFile <> "" Then
e.HasMorePages = True
Else
e.HasMorePages = False
MyNewAcctFile = IO.File.ReadAllText(strErrorFile)
End If
End Sub

I would expect to see something more like:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
Private FileName As String
Private txtFileContents As String
Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
FileName = "C:\Users\mikes\Documents\SomeFile.txt"
txtFileContents = IO.File.ReadAllText(FileName)
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
If txtFileContents.Length > 0 Then
Using printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(txtFileContents, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(txtFileContents, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
txtFileContents = txtFileContents.Substring(charsFitted)
e.HasMorePages = (txtFileContents.Length > 0)
End Using
End If
End Sub
Private Sub PrintDocument1_EndPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.EndPrint
If Not PrintDocument1.PrintController.IsPreview Then
PrintPreviewDialog1.Close()
End If
End Sub
End Class

Related

How can I dispose the image from the following code?

I am using VS 2019.
The presented code should display an animated GIF each time the 'btn_Display' is clicked.
If the image is disposed I've got an error at ImageAnimator.UpdateFrames() in PictureBox.Paint after the second click.
Public Class Form1
Dim animatedImage As Bitmap
Dim currentlyAnimating As Boolean = False
Dim framecounter As Integer
Dim framecount As Integer
Dim framdim As Imaging.FrameDimension
Dim gifFile As String
Private Sub OnFrameChanged(ByVal o As Object, ByVal e As EventArgs)
PictureBox1.Invalidate()
End Sub
Sub AnimateImage()
If Not currentlyAnimating Then
ImageAnimator.Animate(animatedImage, New EventHandler(AddressOf Me.OnFrameChanged))
currentlyAnimating = True
End If
End Sub
Private Sub PictureBox1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
If framecounter < framecount Then
AnimateImage()
ImageAnimator.UpdateFrames()
e.Graphics.DrawImage(Me.animatedImage, New Point(0, 0))
framecounter += 1
Application.DoEvents()
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
PictureBox1.Visible = False
gifFile = "E:\1.gif"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_Display.Click
startGif(gifFile)
End Sub
Sub startGif(ByVal FlName As String)
currentlyAnimating = False
animatedImage = New Bitmap(FlName)
framecounter = 0
PictureBox1.Size = animatedImage.Size
PictureBox1.Visible = True
framdim = New Imaging.FrameDimension(animatedImage.FrameDimensionsList(0))
framecount = animatedImage.GetFrameCount(framdim)
WaitFor_eoAnimation()
animatedImage.Dispose() ' <-----
PictureBox1.Visible = False
End Sub
Private Sub WaitFor_eoAnimation()
' Wait for end of animation
Do
Application.DoEvents()
Loop While framecounter < framecount 'currentlyAnimating
End Sub
End Class
Thanks in advance ... Eitan

How to save an image from Picturebox that load from camera?

I create a simple program that getting image from camera and display it in picturebox using a Aforge library. However, when I try to save the image from picture box. It prompt an error like this " 'System.Runtime.InteropServices.ExternalException' in System.Drawing.dll. A generic error occurred in GDI+. "
I did some research but not found any helpful solution.
Below are my following code use to save the image:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
PictureBox1.Image.Save("C:\a.jpeg", ImageFormat.Jpeg)
End Sub
Updated Code :
Imports AForge
Imports AForge.Video
Imports AForge.Video.DirectShow
Imports AForge.Imaging.Filters
Imports AForge.Imaging
Imports System.Drawing.Imaging
Public Class Form1
Dim Filter As FilterInfoCollection
Dim Camera As VideoCaptureDevice
Dim MINR As Integer = 0
Dim MING As Integer = 0
Dim MINB As Integer = 0
Dim MAXR As Integer = 255
Dim MAXG As Integer = 255
Dim MAXB As Integer = 255
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Filter = New FilterInfoCollection(FilterCategory.VideoInputDevice)
If Filter.Count > 0 Then
For Each ITEM In Filter
ComboBox1.Items.Add(ITEM.Name.ToString())
Next
CheckForIllegalCrossThreadCalls = False
Me.Location = New System.Drawing.Point(Me.Location.X, 0)
Else
MsgBox("NO Camera Found")
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Camera = New VideoCaptureDevice(Filter(ComboBox1.SelectedIndex).MonikerString)
AddHandler Camera.NewFrame, New NewFrameEventHandler(AddressOf Video_NewFrame)
Camera.Start()
ComboBox1.Visible = False
End Sub
Private Sub Video_NewFrame(sender As Object, eventArgs As AForge.Video.NewFrameEventArgs)
Dim ORIGINAL As Bitmap = DirectCast(eventArgs.Frame.Clone(), Bitmap)
Dim FILTER As Bitmap = DirectCast(eventArgs.Frame.Clone(), Bitmap)
Dim CFILTER As New ColorFiltering
CFILTER.Red = New IntRange(MINR, MAXR)
CFILTER.Green = New IntRange(MING, MAXG)
CFILTER.Blue = New IntRange(MINB, MAXB)
CFILTER.ApplyInPlace(FILTER)
Dim GRAY As Grayscale = Grayscale.CommonAlgorithms.BT709
Dim IMAGING As Bitmap = GRAY.Apply(FILTER)
Dim BLOBS As New BlobCounter()
BLOBS.MinHeight = 10
BLOBS.MinWidth = 10
BLOBS.ObjectsOrder = ObjectsOrder.Size
BLOBS.ProcessImage(IMAGING)
Dim Rectangle As Rectangle() = BLOBS.GetObjectsRectangles()
If Rectangle.Count > 0 Then
Dim Rectangle2 As Rectangle = Rectangle(0)
Dim STYLE As Graphics = Graphics.FromImage(ORIGINAL)
Dim CLR As New Pen(Color.Lime, 5)
STYLE.DrawRectangle(CLR, Rectangle2)
STYLE.Dispose()
End If
PictureBoxDefault.Image = ORIGINAL '
PictureBoxFilter.Image = FILTER
End Sub
Private Sub TrackBarMINR_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMINR.Scroll
MINR = TrackBarMINR.Value
LabelMINR.Text = "MINR: " & MINR
End Sub
Private Sub TrackBarMING_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMING.Scroll
MING = TrackBarMING.Value
LabelMING.Text = "MING: " & MING
End Sub
Private Sub TrackBarMINB_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMINB.Scroll
MINB = TrackBarMINB.Value
LabelMINB.Text = "MINB: " & MINB
End Sub
Private Sub TrackBarMAXR_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXR.Scroll
MAXR = TrackBarMAXR.Value
LabelMAXR.Text = "MAXR: " & MAXR
End Sub
Private Sub TrackBarMAXG_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXG.Scroll
MAXG = TrackBarMAXG.Value
LabelMAXG.Text = "MAXG: " & MAXG
End Sub
Private Sub TrackBarMAXB_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXB.Scroll
MAXB = TrackBarMAXB.Value
LabelMAXB.Text = "MAXB: " & MAXB
End Sub
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Try
Camera.SignalToStop()
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnSave.Click
PictureBox1.Image.Save("D:\a.png", ImageFormat.Png)
End Sub
End Class
I had the same issue.
The code below is now working for me.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim img As Bitmap = PictureBox1.Image.Clone
img.Save("Z:\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
Just change "Z:\test.bmp" to your directory, haven't tried any other image formats but this is the only way I have gotten it to work so far.

Visual Basic Advanced Browser

I am creating a browser in Visual Basic, but am having a problem saving my settings.
In advanced options, under the privacy tab i would like to have my browser retain the settings after closing the window. If i click "Never Remember password", and close the window, the settings are not stored.
Also, when I type a URL in, after searching the URL is not updated correctly.
Does anyone have any ideas as to how i can make these parts of my project work?
I am somewhat new to coding, so any tips or extra ideas to add to the Browser would be welcomed and much appreciated as i would like to see this fully functional.
Thank you! :D
Form 1
Imports System.Net
Imports System.IO
Public Class Magycka
Private Declare Sub keybd_event Lib "user32" (ByVal volumeUpOrDown As Byte, ByVal v1 As Byte, ByVal v2 As Integer, ByVal v3 As Integer)
Private Sub Magycka_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
File.Delete("C:\Magycka\history.txt")
For Each link As String In History.lstHistory.Items
File.AppendAllText("C:\Magycka\History.txt", link & vbNewLine)
Next
For Each favoriteName As String In lstName.Items
File.AppendAllText("C:\Magycka\favoriteName.txt", favoriteName & vbNewLine)
Next
For Each favoriteURL As String In lstURL.Items
File.AppendAllText("C:\Magycka\favoriteURL.txt", favoriteURL & vbNewLine)
Next
End Sub
Private Sub tmrDate_Tick(sender As Object, e As EventArgs) Handles tmrDate.Tick
lblTime.Text = DateTime.Now.ToString
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cmbSearchEngine.Items.Add("Google")
cmbSearchEngine.Items.Add("Google Images")
cmbSearchEngine.Items.Add("YouTube")
cmbSearchEngine.SelectedIndex = 0
addTab(TabControl1)
Try
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
txtURL.Text = browser.Url.ToString
Catch ex As Exception
End Try
If My.Settings.homePageorBlankPage = 0 Then
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(My.Settings.homePage)
Else
End If
Try
History.Visible = False
For Each link As String In File.ReadAllLines("C:\Magycka\history.txt")
History.lstHistory.Items.Add(link.ToString)
Next
Catch ex As Exception
End Try
Try
For Each url As String In File.ReadAllLines("C:\Magycka\favoriteURL.txt")
ListBox3.Items.Add(url)
Next
Catch ex As Exception
End Try
Try
ListBox3.SelectedIndex = 0
Catch ex As Exception
End Try
Try
For Each Name As String In File.ReadAllLines("C:\Magycka\favoriteName.txt")
Dim newBookmark As New ToolStripButton
newBookmark.Text = Name
newBookmark.Tag = ListBox3.SelectedItem.ToString
tsBookmarks.Items.Add(newBookmark)
ListBox3.SelectedIndex = ListBox3.SelectedIndex + 1
Next
Catch ex As Exception
End Try
createdBookClick()
End Sub
Private Sub txtURLsearchEngines_KeyUp(sender As Object, e As KeyEventArgs) Handles txtURLsearchEngines.KeyUp
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
Select Case (cmbSearchEngine.SelectedIndex)
Case 0
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.google.com/#q=" + txtURLsearchEngines.Text)
End If
Case 1
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1366&bih=661&q=" + txtURL.Text)
End If
Case 2
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.youtube.com/results?search_query=" + txtURLsearchEngines.Text)
End If
End Select
End Sub
Private Sub txtURL_KeyUp(sender As Object, e As KeyEventArgs) Handles txtURL.KeyUp
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
If e.KeyCode = Keys.Enter Then
browser.Navigate(txtURL.Text)
End If
End Sub
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.GoBack()
End Sub
Private Sub btnForward_Click(sender As Object, e As EventArgs) Handles btnForward.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.GoForward()
End Sub
Private Sub brnRefresh_Click(sender As Object, e As EventArgs) Handles brnRefresh.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Refresh()
End Sub
Private Sub btnURL_Click(sender As Object, e As EventArgs) Handles btnURL.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(txtURL.Text)
End Sub
Private Sub btnVolumeUp_Click(sender As Object, e As EventArgs) Handles btnVolumeUp.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeUp, 0, 0, 0)
End Sub
Private Sub btnVolumeDown_Click(sender As Object, e As EventArgs) Handles btnVolumeDown.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeDown, 0, 0, 0)
End Sub
Private Sub btnMute_Click(sender As Object, e As EventArgs) Handles btnMute.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeMute, 0, 0, 0)
End Sub
Private Sub OptionsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OptionsToolStripMenuItem.Click
AdvancedOptions.Show()
End Sub
Private Sub ViewHistoryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewHistoryToolStripMenuItem.Click
History.Show()
End Sub
Private Sub btnHome_Click(sender As Object, e As EventArgs) Handles btnHome.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(My.Settings.homePage)
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
Select Case (cmbSearchEngine.SelectedIndex)
Case 0
browser.Navigate("https://www.google.com/#q=" + txtURLsearchEngines.Text)
Case 1
browser.Navigate("https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1366&bih=661&q=" = txtURLsearchEngines.Text)
Case 2
browser.Navigate("https://www.youtube.com/results?search_query=" + txtURLsearchEngines.Text)
End Select
End Sub
Private Sub NewTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewTabToolStripMenuItem.Click
addTab(TabControl1)
End Sub
Private Sub CloseTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseTabToolStripMenuItem.Click
removeTab()
End Sub
Public Sub addTab(ByRef TabControl As TabControl)
Dim browser As New webBrowserfunction
Dim tab As New TabPage
browser.Tag = tab
tab.Tag = browser
TabControl1.TabPages.Add(tab)
tab.Controls.Add(browser)
browser.Dock = DockStyle.Fill
browser.Navigate(My.Settings.homePage)
TabControl1.SelectedTab = tab
End Sub
Public Sub addTabfromHistory(ByRef TabControl As TabControl, ByRef link As String)
Dim browser As New webBrowserfunction
Dim tab As New TabPage
browser.Tag = tab
tab.Tag = browser
TabControl1.TabPages.Add(tab)
tab.Controls.Add(browser)
browser.Dock = DockStyle.Fill
browser.Navigate(link)
TabControl1.SelectedTab = tab
End Sub
Public Sub removeTab()
If TabControl1.TabPages.Count <> 0 Then
TabControl1.TabPages.Remove(TabControl1.SelectedTab)
End If
End Sub
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Try
txtURL.Text = browser.Url.ToString
Catch ex As Exception
End Try
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
Dim newWindow As New Magycka
newWindow.Show()
End Sub
Private Sub UndoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UndoToolStripMenuItem.Click
txtURL.Undo()
End Sub
Private Sub RedoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RedoToolStripMenuItem.Click
txtURL.ClearUndo()
End Sub
Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CutToolStripMenuItem.Click
txtURL.Cut()
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
txtURL.Copy()
End Sub
Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click
txtURL.Paste()
End Sub
Private Sub SelectAllToolStripMenuItem_Click(sender As Object, e As EventArgs)
txtURL.SelectAll()
End Sub
Private Sub SaveSourceCodeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveSourceCodeToolStripMenuItem.Click
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Dim fileName As String = InputBox("Enter FileName:", "Save HTML", ".txt")
Dim path As String = "C:\Magycka\" & fileName
Try
If File.Exists(path) Then
Dim allText As String
allText = browser.DocumentText
File.WriteAllText(path, allText)
Else
File.Create(path).Dispose()
Dim allText As String
allText = browser.DocumentText
File.WriteAllText(path, allText)
End If
Catch ex As Exception
End Try
End Sub
Private Sub addBookmarks()
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Dim newBookmark As New ToolStripButton
newBookmark.Text = TabControl1.SelectedTab.Text
newBookmark.Tag = browser.Url
tsBookmarks.Items.Add(newBookmark)
lstName.Items.Add(TabControl1.SelectedTab.Text)
lstURL.Items.Add(browser.Url.ToString)
AddHandler newBookmark.Click, AddressOf newBookmarkClick
End Sub
Private Sub newBookmarkClick(sender As Object, e As EventArgs)
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
If TypeOf sender Is ToolStripButton Then
browser.Navigate(CType(sender, ToolStripButton).Tag)
End If
End Sub
Private Sub createdBookClick()
For Each item As ToolStripButton In tsBookmarks.Items
AddHandler item.Click, AddressOf bookClick
Next
End Sub
Private Sub bookClick(sender As Object, e As EventArgs)
txtURL.Text = CType(sender, ToolStripButton).Tag
bookNav()
End Sub
Private Sub bookNav()
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
browser.Navigate(txtURL.Text)
End Sub
Private Sub BookmarkPageToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BookmarkPageToolStripMenuItem.Click
addBookmarks()
End Sub
End Class
Advanced Options
Imports System.Net
Imports System.IO
Public Class Magycka
Private Declare Sub keybd_event Lib "user32" (ByVal volumeUpOrDown As Byte, ByVal v1 As Byte, ByVal v2 As Integer, ByVal v3 As Integer)
Private Sub Magycka_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
File.Delete("C:\Magycka\history.txt")
For Each link As String In History.lstHistory.Items
File.AppendAllText("C:\Magycka\History.txt", link & vbNewLine)
Next
For Each favoriteName As String In lstName.Items
File.AppendAllText("C:\Magycka\favoriteName.txt", favoriteName & vbNewLine)
Next
For Each favoriteURL As String In lstURL.Items
File.AppendAllText("C:\Magycka\favoriteURL.txt", favoriteURL & vbNewLine)
Next
End Sub
Private Sub tmrDate_Tick(sender As Object, e As EventArgs) Handles tmrDate.Tick
lblTime.Text = DateTime.Now.ToString
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cmbSearchEngine.Items.Add("Google")
cmbSearchEngine.Items.Add("Google Images")
cmbSearchEngine.Items.Add("YouTube")
cmbSearchEngine.SelectedIndex = 0
addTab(TabControl1)
Try
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
txtURL.Text = browser.Url.ToString
Catch ex As Exception
End Try
If My.Settings.homePageorBlankPage = 0 Then
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(My.Settings.homePage)
Else
End If
Try
History.Visible = False
For Each link As String In File.ReadAllLines("C:\Magycka\history.txt")
History.lstHistory.Items.Add(link.ToString)
Next
Catch ex As Exception
End Try
Try
For Each url As String In File.ReadAllLines("C:\Magycka\favoriteURL.txt")
ListBox3.Items.Add(url)
Next
Catch ex As Exception
End Try
Try
ListBox3.SelectedIndex = 0
Catch ex As Exception
End Try
Try
For Each Name As String In File.ReadAllLines("C:\Magycka\favoriteName.txt")
Dim newBookmark As New ToolStripButton
newBookmark.Text = Name
newBookmark.Tag = ListBox3.SelectedItem.ToString
tsBookmarks.Items.Add(newBookmark)
ListBox3.SelectedIndex = ListBox3.SelectedIndex + 1
Next
Catch ex As Exception
End Try
createdBookClick()
End Sub
Private Sub txtURLsearchEngines_KeyUp(sender As Object, e As KeyEventArgs) Handles txtURLsearchEngines.KeyUp
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
Select Case (cmbSearchEngine.SelectedIndex)
Case 0
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.google.com/#q=" + txtURLsearchEngines.Text)
End If
Case 1
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1366&bih=661&q=" + txtURL.Text)
End If
Case 2
If e.KeyCode = Keys.Enter Then
browser.Navigate("https://www.youtube.com/results?search_query=" + txtURLsearchEngines.Text)
End If
End Select
End Sub
Private Sub txtURL_KeyUp(sender As Object, e As KeyEventArgs) Handles txtURL.KeyUp
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
If e.KeyCode = Keys.Enter Then
browser.Navigate(txtURL.Text)
End If
End Sub
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.GoBack()
End Sub
Private Sub btnForward_Click(sender As Object, e As EventArgs) Handles btnForward.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.GoForward()
End Sub
Private Sub brnRefresh_Click(sender As Object, e As EventArgs) Handles brnRefresh.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Refresh()
End Sub
Private Sub btnURL_Click(sender As Object, e As EventArgs) Handles btnURL.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(txtURL.Text)
End Sub
Private Sub btnVolumeUp_Click(sender As Object, e As EventArgs) Handles btnVolumeUp.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeUp, 0, 0, 0)
End Sub
Private Sub btnVolumeDown_Click(sender As Object, e As EventArgs) Handles btnVolumeDown.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeDown, 0, 0, 0)
End Sub
Private Sub btnMute_Click(sender As Object, e As EventArgs) Handles btnMute.Click
Call keybd_event(System.Windows.Forms.Keys.VolumeMute, 0, 0, 0)
End Sub
Private Sub OptionsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OptionsToolStripMenuItem.Click
AdvancedOptions.Show()
End Sub
Private Sub ViewHistoryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewHistoryToolStripMenuItem.Click
History.Show()
End Sub
Private Sub btnHome_Click(sender As Object, e As EventArgs) Handles btnHome.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
browser.Navigate(My.Settings.homePage)
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim browser As webBrowserfunction = Me.TabControl1.SelectedTab.Tag
Select Case (cmbSearchEngine.SelectedIndex)
Case 0
browser.Navigate("https://www.google.com/#q=" + txtURLsearchEngines.Text)
Case 1
browser.Navigate("https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1366&bih=661&q=" = txtURLsearchEngines.Text)
Case 2
browser.Navigate("https://www.youtube.com/results?search_query=" + txtURLsearchEngines.Text)
End Select
End Sub
Private Sub NewTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewTabToolStripMenuItem.Click
addTab(TabControl1)
End Sub
Private Sub CloseTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseTabToolStripMenuItem.Click
removeTab()
End Sub
Public Sub addTab(ByRef TabControl As TabControl)
Dim browser As New webBrowserfunction
Dim tab As New TabPage
browser.Tag = tab
tab.Tag = browser
TabControl1.TabPages.Add(tab)
tab.Controls.Add(browser)
browser.Dock = DockStyle.Fill
browser.Navigate(My.Settings.homePage)
TabControl1.SelectedTab = tab
End Sub
Public Sub addTabfromHistory(ByRef TabControl As TabControl, ByRef link As String)
Dim browser As New webBrowserfunction
Dim tab As New TabPage
browser.Tag = tab
tab.Tag = browser
TabControl1.TabPages.Add(tab)
tab.Controls.Add(browser)
browser.Dock = DockStyle.Fill
browser.Navigate(link)
TabControl1.SelectedTab = tab
End Sub
Public Sub removeTab()
If TabControl1.TabPages.Count <> 0 Then
TabControl1.TabPages.Remove(TabControl1.SelectedTab)
End If
End Sub
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Try
txtURL.Text = browser.Url.ToString
Catch ex As Exception
End Try
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
Dim newWindow As New Magycka
newWindow.Show()
End Sub
Private Sub UndoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UndoToolStripMenuItem.Click
txtURL.Undo()
End Sub
Private Sub RedoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RedoToolStripMenuItem.Click
txtURL.ClearUndo()
End Sub
Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CutToolStripMenuItem.Click
txtURL.Cut()
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
txtURL.Copy()
End Sub
Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click
txtURL.Paste()
End Sub
Private Sub SelectAllToolStripMenuItem_Click(sender As Object, e As EventArgs)
txtURL.SelectAll()
End Sub
Private Sub SaveSourceCodeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveSourceCodeToolStripMenuItem.Click
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Dim fileName As String = InputBox("Enter FileName:", "Save HTML", ".txt")
Dim path As String = "C:\Magycka\" & fileName
Try
If File.Exists(path) Then
Dim allText As String
allText = browser.DocumentText
File.WriteAllText(path, allText)
Else
File.Create(path).Dispose()
Dim allText As String
allText = browser.DocumentText
File.WriteAllText(path, allText)
End If
Catch ex As Exception
End Try
End Sub
Private Sub addBookmarks()
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
Dim newBookmark As New ToolStripButton
newBookmark.Text = TabControl1.SelectedTab.Text
newBookmark.Tag = browser.Url
tsBookmarks.Items.Add(newBookmark)
lstName.Items.Add(TabControl1.SelectedTab.Text)
lstURL.Items.Add(browser.Url.ToString)
AddHandler newBookmark.Click, AddressOf newBookmarkClick
End Sub
Private Sub newBookmarkClick(sender As Object, e As EventArgs)
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
If TypeOf sender Is ToolStripButton Then
browser.Navigate(CType(sender, ToolStripButton).Tag)
End If
End Sub
Private Sub createdBookClick()
For Each item As ToolStripButton In tsBookmarks.Items
AddHandler item.Click, AddressOf bookClick
Next
End Sub
Private Sub bookClick(sender As Object, e As EventArgs)
txtURL.Text = CType(sender, ToolStripButton).Tag
bookNav()
End Sub
Private Sub bookNav()
Dim browser As webBrowserfunction = TabControl1.SelectedTab.Tag
browser.Navigate(txtURL.Text)
End Sub
Private Sub BookmarkPageToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BookmarkPageToolStripMenuItem.Click
addBookmarks()
End Sub
End Class
History
Imports System.IO
Public Class History
Private Sub History_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = True
Me.Visible = False
For Each link As String In lstHistory.Items
File.AppendAllText("C:\Magycka\History.txt", link & vbNewLine)
Next
End Sub
Private Sub btnClearHis_Click(sender As Object, e As EventArgs) Handles btnClearHis.Click
lstHistory.Items.Clear()
System.IO.File.Delete("C:\Magycka\History.txt")
End Sub
Private Sub btnCloseHis_Click(sender As Object, e As EventArgs) Handles btnCloseHis.Click
For Each link As String In lstHistory.Items
File.AppendAllText("C:\Magycka\History.txt", link & vbNewLine)
Next
Close()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
lstHistory.Items.Remove(lstHistory.SelectedItem)
End Sub
Private Sub lstHistory_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles lstHistory.MouseDoubleClick
Magycka.addTabfromHistory(Magycka.TabControl1, lstHistory.SelectedItem.ToString)
End Sub
End Class

System.I.O the process cannot access the file because it is being used by another process

I'm designing a program that calculates the average of scores. the program works great except when I try to add a name and a number from textbox into the textfile it returns an error. I believe that I have closed the file every time it has been used. my code is:
Public Class Form4
Public Function GetNumberOfLines(ByVal file_path As String) As Integer
Using sr As New StreamReader("C:\file.txt")
Dim NumberOfLines As Integer
Do While sr.Peek >= 0 'a pre test loop to read lines
sr.ReadLine()
NumberOfLines += 1
Loop
Return NumberOfLines
sr.Close() 'closes file after it is read
sr.Dispose()
End Using
End Function
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Hide()
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim FILE_NAME As String = "C:\file.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Close()
objWriter.Write(TextBox5.Text)
MsgBox("Text written to file")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Using sr As New System.IO.StreamReader("C:\file.txt")
Dim LofInt As New List(Of Integer)
While sr.Peek <> -1
Dim line As String = sr.ReadLine
Dim intValue As String = String.Empty
For Each c As Char In line
If IsNumeric(c) Then
intValue += c
End If
Next
LofInt.Add(intValue)
End While
sr.Close()
sr.Dispose()
LofInt.Sort()
For Each i In LofInt
Scores.Items.Add(i)
Next
Dim sum As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
TextBox4.Text = sum
sr.Close()
sr.Dispose()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\file.txt")
TextBox2.Text = GetNumberOfLines("C:\file.txt")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sum As Decimal
Dim avg As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
avg = sum / (GetNumberOfLines("C:\file.txt"))
TextBox3.Text = avg
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Close()
End Sub
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
TextBox1.Clear()
TextBox2.Clear()
Scores.Items.Clear()
TextBox4.Clear()
TextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\file.txt")
TextBox2.Text = GetNumberOfLines("C:\file.txt")
Using sr As New System.IO.StreamReader("C:\file.txt")
Dim LofInt As New List(Of Integer)
While sr.Peek <> -1
Dim line As String = sr.ReadLine
Dim intValue As String = String.Empty
For Each c As Char In line
If IsNumeric(c) Then
intValue += c
End If
Next
LofInt.Add(intValue)
End While
LofInt.Sort()
For Each i In LofInt
Scores.Items.Add(i)
Next
Dim sum As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
TextBox4.Text = sum
sr.Close()
sr.Dispose()
End Using
End Sub
Dim objWriter As New System.IO.StreamWriter(FILE_NAME) is where the error occurs

Is it possible to print or save the picturebox with other picture box within it

I am a vb.net beginner. I got a project that I need to do function that enabled user to add new picture(which is a new picturebox) and move it in a picture box. I have made these two happened but I don`t know how to make the picturebox(that allow new picturebox move inside) save as bitmap/jpg into database. Is that possible to do that.If yes, how?
Public Class Form1
Private btn As Button ' this is a reference object
Private pic As PictureBox
Private ptX, ptY As Integer
Private drag As Boolean
Private Sub nodepic_MouseDown(ByVal senderPic As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Button = MouseButtons.Left Then
drag = True
pic = CType(senderPic, PictureBox)
ptX = e.X : ptY = e.Y
End If
If pic.Focused Then
clearButton.Enabled = True
End If
End Sub
Private Sub nodepic_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If drag Then
If pic.Location.X >= 1 AndAlso pic.Location.Y >= 1 AndAlso
(pic.Location.X + pic.Width) <= panelPictureBox.Width - 5 AndAlso
(pic.Location.Y + pic.Height) <= panelPictureBox.Height - 5 Then
pic.Location = New Point(pic.Location.X + e.X - ptX, pic.Location.Y + e.Y - ptY)
Me.Refresh()
Else
drag = False
pic.Location = New Point(pic.Location.X + e.X - ptX, pic.Location.Y + e.Y - ptY)
End If
End If
End Sub
Private Sub node_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
drag = False
End Sub
Private Sub deleteButton(senderPic As Object, e As EventArgs)
Dim delete As DialogResult
delete = MessageBox.Show("Are you sure to delete this icon?", "Delete Icon", MessageBoxButtons.YesNo)
If delete = Windows.Forms.DialogResult.Yes Then
senderPic.Dispose()
locationLabel.Text = String.Empty
End If
End Sub
Private Sub locationButton(senderPic As Object, e As System.Windows.Forms.MouseEventArgs)
pic.Location = New Point(pic.Location.X + e.X - ptX, pic.Location.Y + e.Y - ptY)
locationLabel.Text = pic.Location.ToString()
End Sub
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
Dim picBox As New PictureBox
If e.Node.Name.Equals("red") Then
picBox.Image = ImageList1.Images(0)
End If
If e.Node.Name.Equals("orange") Then
picBox.Image = ImageList1.Images(1)
End If
picBox.Location = New Point(10, 10)
panelPictureBox.Controls.Add(picBox)
action(picBox)
End Sub
Private Sub action(sender As PictureBox)
AddHandler sender.MouseDown, AddressOf nodepic_MouseDown
AddHandler sender.MouseMove, AddressOf nodepic_MouseMove
AddHandler sender.MouseUp, AddressOf node_MouseUp
AddHandler sender.MouseDoubleClick, AddressOf deleteButton
AddHandler sender.MouseClick, AddressOf locationButton
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
panelPictureBox.Enabled = True
panelPictureBox.BackColor = Color.White
End Sub
Private Sub clearButton_Click(senderPic As Object, e As EventArgs) Handles clearButton.Click
pic.Dispose()
End Sub**strong text**
End Class
You can save the PictureBox, along with its "child" PictureBoxes, to a Bitmap using code like this:
Dim bmp As New Bitmap(panelPictureBox.Width, panelPictureBox.Height)
panelPictureBox.DrawToBitmap(bmp, panelPictureBox.ClientRectangle)
Next you save it to memory by writing it out to a MemoryStream. Note that you can specify the format in the second parameter:
Dim ms As New System.IO.MemoryStream()
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Finally, you can obtain a byte array from the resulting MemoryStream:
Dim bytes() As Byte = ms.ToArray
' ... save "bytes" to your database ...
if you need to print the image inside the picturebox then you should insert printdialog ,printdocument in side the design of the form then copy the code below
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
PrintDialog1 = New PrintDialog
PrintDialog1.Document = PrintDocument1 'pbxLogo.Image
Dim r As DialogResult = PrintDialog1.ShowDialog
If r = DialogResult.OK Then
PrintDocument1.Print()
End If
End Sub
Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
e.Graphics.DrawImage(PictureBox1.Image, 0, 0)
End Sub