How to select a tray on a printer thorugh code when printing from a word document in VB (VS2019) - vba

Hi I'm trying to create a word document and then print it with VB in visual studio 2019.
Creation works ok, the document saves fine, and prints fine to the general tray but I cannot get the application to send the print job to a specified tray. the prints will just come out of the default paper try
the customers have an array of different printer makes and models
ive tried printing the document through word, ive also tried changing the printer itself on the computer to set the tray then change it back after
TRY 1
Dim intTray As Integer = varibleNumber
If intTray = 1 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterUpperBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterUpperBin
ElseIf intTray = 2 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterMiddleBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterMiddleBin
ElseIf intTray = 3 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterLowerBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterLowerBin
Else
'else print default tray
oWord.ActiveDocument.p.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterDefaultBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterDefaultBin
End If
TRY 2
Dim intTray As Integer = varibleNumber
Dim oPS As New System.Drawing.Printing.PrinterSettings
If intTray = 1 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 1")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 1"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 1"
ElseIf intTray = 2 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 2")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 2"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 2"
ElseIf intTray = 3 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 3")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 3"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 3"
Else
'else print default tray
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Automatically Select")
End If
modPrint.printWordDoc(oWord)
Pages just come out of the main printer tray.
Any help much appreciated

One quick solution that pops to my mind is to use VBA Printer Setup Dialog to change the Tray on your printer settings. Try executing this line of code and change the options on the printer you're using:
Application.Dialogs(xlDialogPrinterSetup).Show
Edit:
Try using this code specific to VB framework. It's a valid starting point, since it allows you to select which print to use:
Public Sub Printing(printer As String)
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Specify the printer to use.
pd.PrinterSettings.PrinterName = printer
If pd.PrinterSettings.IsValid then
pd.Print()
Else
MessageBox.Show("Printer is invalid.")
End If
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
You can find more info here on Microsoft Documentation.
Hope this helps.

Managed to resolve the issue finally :) each printer has its own tray numbers for every tray, even if they are labelled Tray1 Tray2 etc.
so had to look through the papersources find when the source name equalled the tray number I wanted then grab the rawkind value of that source and use that as the tray number when allocating to the word firstpagetray
Dim intTray As Integer = <tray number i'm looking for>
Dim oPS As New System.Drawing.Printing.PrinterSettings
Dim paper_Source As PaperSource = New PaperSource
Dim i As Integer = 0
For Each ps As PaperSource In oPS.PaperSources
If ps.SourceName.Contains(intTray.ToString) Then
i = ps.RawKind
Exit For
End If
Next
oWord.ActiveDocument.PageSetup.FirstPageTray = i
Hope this helps others with the same issue

Related

Programmatically printing WebBrowser and setting its PrinterSettings in VB

I am trying to find a way to set PrinterSettings when printing contents of WebBrowser similar to the following code
Dim doc As PrintDocument = New PrintDocument()
With doc
.PrinterSettings = New PrinterSettings()
With .PrinterSettings
.PrinterName = "PrinterName"
.PrintToFile = True
.PrintFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "test.pdf")
End With
End With
doc.Print()
I converted this from a C# code I've found that tells how to set PrinterSettings programmatically.
Is there a way to combine the code above with WebBrowser.Print() in order to print HTML and set PrinterSettings programmatically
I have tried doing it like this thinking that this code might set default printer to Microsoft Print to PDF
Dim doc As PrintDocument = New PrintDocument()
With doc
.PrinterSettings = New PrinterSettings()
With .PrinterSettings
.PrinterName = "Microsoft Print to PDF"
.PrintToFile = True
.PrintFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "test.pdf")
End With
End With
WebBrowser.Print()
But it prints on the default printer and not on Microsoft Print to PDF
Edit: The WebBrowser contains the document I'm trying to print in HTML Format and some inline CSS. The WebBrowser don't have a UI, It is a plain code Declared as Private WithEvents WebBrowser As WebBrowser. Hope this helps clear my problem, thanks.
Edit(2): Setting the Default Printer have been problematic to me because of the printer setting "let windows manage my printers." Unchecking this allow the application to set the default printer. credits to K J
Try This :
Vote for me if I've helped you.
Dim doc As New PrintDocument()
With doc
With .PrinterSettings
.PrinterName = "PrinterName" ' exam: Fax
.PrintToFile = True
.PrintFileName = "The location of the file you want to print with the formula" ' exam -> C:\CV.pdf
End With
End With
doc.Print()

Printing an external PDF document in VB.net

I know this question has been asked before, but my situation is a bit wonky.
Basically, I'm trying to print a PDF file that I've generated using a previous Windows Form. I can find the file no problem, and I used the following code which I found off MSDN's help forums:
Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "C:\534679.pdf" 'This is the file name
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
So far so good, but everytime I press the button to run this code, it keeps asking me to save it as a PDF file instead, as shown below:
I've also tried adding a PrintDialog to the Windows Form, getting it to pop up, and I can select the printer I want to use from there, but even after selecting the printer it still asks me to print to PDF Document instead.
What am I doing wrong?
To print massive PDF documents with VB.Net you can use LVBPrint and run it via command line:
http://www.lvbprint.de/html/gsbatchprint1.html
For Example:
C:\temp\gsbatchprint64\gsbatchprintc.exe -P \\server\printer -N A3 -O Port -F C:\temp\gsbatchprint64\Test*.pdf -I Tray3
I use the following function in my application:
' print a pdf with lvbrint
Private Function UseLvbPrint(ByVal oPrinter As tb_Printer, fileName As String, portrait As Boolean, sTray As String) As String
Dim lvbArguments As String
Dim lvbProcessInfo As ProcessStartInfo
Dim lvbProcess As Process
Try
Dim sPrinterName As String
If portrait Then
lvbArguments = String.Format(" -P ""{0}"" -O Port -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
Else
lvbArguments = String.Format(" -P ""{0}"" -O Land -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
End If
lvbProcessInfo = New ProcessStartInfo()
lvbProcessInfo.WindowStyle = ProcessWindowStyle.Hidden
' location of gsbatchprintc.exe
lvbProcessInfo.FileName = LvbLocation
lvbProcessInfo.Arguments = lvbArguments
lvbProcessInfo.UseShellExecute = False
lvbProcessInfo.RedirectStandardOutput = True
lvbProcessInfo.RedirectStandardError = True
lvbProcessInfo.CreateNoWindow = False
lvbProcess = Process.Start(lvbProcessInfo)
'
' Read in all the text from the process with the StreamReader.
'
Using reader As StreamReader = lvbProcess.StandardOutput
Dim result As String = reader.ReadToEnd()
WriteLog(result)
End Using
Using readerErr As StreamReader = lvbProcess.StandardError
Dim resultErr As String = readerErr.ReadToEnd()
If resultErr.Trim() > "" Then
WriteLog(resultErr)
lvbProcess.Close()
Return resultErr
End If
End Using
If lvbProcess.HasExited = False Then
lvbProcess.WaitForExit(3000)
End If
lvbProcess.Close()
Return ""
Catch ex As Exception
Return ex.Message
End Try
End Function
I discourage on using AcrRd32.exe as it doesn't work with massive printings.
First, to be able to select a Printer, you'll have to use a PrintDialog and PrintDocument to send graphics to print to the selected printer.
Imports System.Drawing.Printing
Private WithEvents p_Document As PrintDocument = Nothing
Private Sub SelectPrinterThenPrint()
Dim PrintersDialog As New PrintDialog()
If PrintersDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
Try
p_Document = New PrintDocument()
PrintersDialog.Document = p_Document
AddHandler p_Document.PrintPage, AddressOf HandleOnPrintPage
Catch CurrentException As Exception
End Try
End If
End Sub
Private Sub HandleOnPrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles p_Document.PrintPage
Dim MorePagesPending As Boolean = False
'e.Graphics.Draw...(....)
'e.Graphics.DrawString(....)
' Draw everything...
If MorePagesPending Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
That's what I'm doing since I usually have custom objects to print.
But to print PDF Files, you must understand that PDF means absolutely nothing to dotNet. Unlike common images like Bitmaps (.bmp) or Ping images (.png) the dotNet doesn't seem to have any inbuilt parser/decoder for reading, displaying and printing PDF files.
So you must use a third party application, thrid party library or your own custom PDF parser/layout generator in order to be able to send pages to print to your printer.
That's why you can't launch a hidden (not visible) process of Acrobat Reader with the command "print". You won't be able to select a printer but will direct to the default one instead !
You can however launch the Acrobat Reader process just to open the file, and do the printing manipulations (select a printer) inside Acrobat Reader (you're outside dotNet coding now)
A workaround for your may aslo to select another default printer by opening Acrobat Reader, and print one blank page on an actual working printer. This should deselect your FoxIt thing in favour of an actual printer..
This code will help you to print in a specific printer.
The sample print a file using a ProcessStartInfo and a specific printer you can change the printer to use in the process.
If the print process is not finished after 10 seconds we kill the print process.
'Declare a printerSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click
Try
dim fileName As String = "C:\534679.pdf"
'Get de the default printer in the system
defaultPrinterSetting = DocumentPrinter.GetDefaultPrinterSetting
'uncomment if you want to change the default printer before print
'DocumentPrinter.ChangePrinterSettings(defaultPrinterSetting)
'print your file
If PrintFile(fileName, defaultPrinterSetting) then
msgbox ("your print file success message")
else
msgbox ("your print file failed message")
end if
Catch ex As Exception
mssbox(ex.Message.toString)
End Try
End Sub
Public NotInheritable Class DocumentPrinter
Shared Sub New()
End Sub
Public Shared Function PrintFile(ByVal fileName As String, printerSetting As System.Drawing.Printing.PrinterSettings) As Boolean
Dim printProcess As System.Diagnostics.Process = Nothing
Dim printed As Boolean = False
Try
If PrinterSetting IsNot Nothing Then
Dim startInfo As New ProcessStartInfo()
startInfo.Verb = "Print"
startInfo.Arguments = defaultPrinterSetting.PrinterName ' <----printer to use----
startInfo.FileName = fileName
startInfo.UseShellExecute = True
startInfo.CreateNoWindow = True
startInfo.WindowStyle = ProcessWindowStyle.Hidden
Using print As System.Diagnostics.Process = Process.Start(startInfo)
'Close the application after X milliseconds with WaitForExit(X)
print.WaitForExit(10000)
If print.HasExited = False Then
If print.CloseMainWindow() Then
printed = True
Else
printed = True
End If
Else
printed = True
End If
print.Close()
End Using
Else
Throw New Exception("Printers not found in the system...")
End If
Catch ex As Exception
Throw
End Try
Return printed
End Function
''' <summary>
''' Change the default printer using a print dialog Box
''' </summary>
''' <param name="defaultPrinterSetting"></param>
''' <remarks></remarks>
Public Shared Sub ChangePrinterSettings(ByRef defaultPrinterSetting As System.Drawing.Printing.PrinterSettings)
Dim printDialogBox As New PrintDialog
If printDialogBox.ShowDialog = Windows.Forms.DialogResult.OK Then
If printDialogBox.PrinterSettings.IsValid Then
defaultPrinterSetting = printDialogBox.PrinterSettings
End If
End If
End Sub
''' <summary>
''' Get the default printer settings in the system
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetDefaultPrinterSetting() As System.Drawing.Printing.PrinterSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
For Each printer As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
defaultPrinterSetting = New System.Drawing.Printing.PrinterSettings
defaultPrinterSetting.PrinterName = printer
If defaultPrinterSetting.IsDefaultPrinter Then
Return defaultPrinterSetting
End If
Next
Return defaultPrinterSetting
End Function
End Class
I used this code to print my PDF files on VB NET:
Dim PrintPDF As New ProcessStartInfo
PrintPDF.UseShellExecute = True
PrintPDF.Verb = "print"
PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
PrintPDF.FileName = dirName & fileName 'fileName is a string parameter
Process.Start(PrintPDF)
When you do this, process remains open with a adobe reader window that users have to close manually. I wanted to avoid user's interaction, just want them to get their documents. So, I added a few code lines to kill process:
Private Sub killProcess(ByVal processName As String)
Dim procesos As Process()
procesos = Process.GetProcessesByName(processName) 'I used "AcroRd32" as parameter
If procesos.Length > 0 Then
For i = procesos.Length - 1 To 0 Step -1
procesos(i).Kill()
Next
End If
End Sub
If you put the kill process method right after the print method you won't get your document printed (I guess this is because process is killed before it is sent to printer). So, between these 2 methods, I added this line:
Threading.Thread.Sleep(10000) ' 10000 is the milisecs after the next code line is executed
And with this my code worked as I wanted. Hope it helps you!

Print report directly, without print dialogue box and report viewer

I need to print my reports directly to printer:
1) Without showing print dialogue box
2) Without showing the Reportviewer
I was suggested the following code:
Dim printerSettings As New PrinterSettings()
Dim printDialog As New PrintDialog()
printDialog.PrinterSettings = printerSettings
printDialog.AllowPrintToFile = False
printDialog.AllowSomePages = True
printDialog.UseEXDialog = True
Dim result As DialogResult = printDialog.ShowDialog()
If result = DialogResult.Cancel Then
Return
End If
Me.rptSalesReport.PrintOptions.PrinterName = printerSettings.PrinterName
Me.rptSalesReport.PrintToPrinter(printerSettings.Copies, False, 0, 0)
But I am receiving error on the last two lines, where I put the name of my reports,
rptSalesReport. It says:
rptSalesReport is not defined.
While the rptSalesReport is there in my project and I can view it through report viewer.
Please advise.
Thanks

Programmatically set Custom Paper Size for Crystal Report

I have created custom paper Size "SUPP 15 x 14" in Setting - Printers - File - Server Properties. Now I’m trying to set custom Paper Size for Crystal Report using VB.net 2005.
When I run report from VB.net, the Crystal report viewer shows the correct preview for custom paper size but when I give print command it prints with the default printer paper size. (e.g Letter)
Here's the code I'm using to print:
Public Sub ...
'...
Dim ObjCrReport as new ReportDocument
'...
ObjCrReport.SetDataSource(ObjPrintDataSet.Tables("PrintData"))
SetReportPageSize("SUPP 15 x 14", 1)
'...
End Sub
Private Sub BtnPrintDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPrintDoc.Click
Try
'Print command
ObjCrReport.PrintToPrinter(1, False, 0, 0)
Catch ex As Exception
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Sub SetReportPageSize(ByVal mPaperSize As String, ByVal PaperOrientation As Integer)
Try
Dim ObjPrinterSetting As New System.Drawing.Printing.PrinterSettings
Dim PkSize As New System.Drawing.Printing.PaperSize
ObjPrinterSetting.PrinterName = "Epson FX1170"
For i As Integer = 0 To ObjPrinterSetting.PaperSizes.Count - 1
If ObjPrinterSetting.PaperSizes.Item(i).PaperName = mPaperSize.Trim Then
PkSize = ObjPrinterSetting.PaperSizes.Item(i)
Exit For
End If
Next
If PkSize IsNot Nothing Then
Dim myAppPrintOptions As CrystalDecisions.CrystalReports.Engine.PrintOptions = ObjCrReport.PrintOptions
myAppPrintOptions.PrinterName = "Epson FX1170"
myAppPrintOptions.PaperSize = CType(PkSize.RawKind, CrystalDecisions.Shared.PaperSize)
ObjCrReport.PrintOptions.PaperOrientation = IIf(PaperOrientation = 1, _
CrystalDecisions.Shared.PaperOrientation.Portrait, _
CrystalDecisions.Shared.PaperOrientation.Landscape)
End If
PkSize = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
If I use myAppPrintOptions.PaperSize = PaperSize.PaperLegal, then Print Preview & Printing appear correct, but I want to set custom paper size which is not showing in the PaperSize class.
What’s wrong with above code? Why is it printing Letter Size where Crystal report preview otherwise shows custom paper in the size preview? Is there a better way to accomplish my goal?
This Method works with an Epson LX-300+ ii Dot-Matrix Printer and later models
If you are using a Printer especially for Printing Receipts
here are the steps on how to set your printer for desired paper size
First Set up Printer to be used:
Go to Devices and Printers
in Printers select the Printer you are going to use and click - right click Printer Properties
Click Preferences... Button. Under Main Tab - Change Document Size to User Defined
a new New Window will appear.
in Paper Size Name specify the name (i.e. OR Paper)
and change paper width and height as desired
Click Save then OK
then set your printer by Pressing right click then set as Default Printer
Add these line of code for your printing. You can still use parameters and datasets.
Dim c As Integer
Dim doctoprint As New System.Drawing.Printing.PrintDocument()
doctoprint.PrinterSettings.PrinterName = "EPSON L1300 Series"
Dim rawKind As Integer
For c = 0 To doctoprint.PrinterSettings.PaperSizes.Count - 1
If doctoprint.PrinterSettings.PaperSizes(c).PaperName = "OR Receipts" Then
rawKind = CInt(doctoprint.PrinterSettings.PaperSizes(c).GetType().GetField("kind", Reflection.BindingFlags.Instance Or
Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes(c)))
Exit For
End If
Next
Report1.PrintOptions.PaperSize = CType(rawKind, CrystalDecisions.Shared.PaperSize)
frmPreview.CrystalReportViewer1.ReportSource = Report1
Report1.PrintToPrinter(1, False, 1, 1)
you can do as this
var rep = new YursCrystalReport();
var printerSettings = new System.Drawing.Printing.PrinterSettings();
var pSettings = new System.Drawing.Printing.PageSettings(printerSettings);
pSettings.PaperSize = new System.Drawing.Printing.PaperSize("newsize", 3000, 3000);//custom size hundredths (100=1 inch)
pSettings.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);
rep.PrintOptions.DissociatePageSizeAndPrinterPaperSize = true;
rep.PrintOptions.CopyFrom(printerSettings, pSettings);

Adding Progress bar while loading Image list to listbox using vb.net

I am trying to add Images using open file dialog and folder browse dialog and populating the image list to listbox.While adding these Images I need to show the progress bar for every image it loads.
I am trying to get that but when the value of the progress bar say something around 25 0r 40 it is stopping at that point but I need to show the progress bar until it completes the 100% and then populates the Image list.
How do I do that?
Here is my code:
Private Sub AddImages_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddImages.Click
If Not Directory.Exists(Application.StartupPath + "\Backup\") = True Then
Directory.CreateDirectory(Application.StartupPath + "\Backup\")
End If
OpenFileDialog1.FileName = "Select a Image"
OpenFileDialog1.Multiselect = True
OpenFileDialog1.InitialDirectory = "C:\Users\Public\Pictures\Sample Pictures"
OpenFileDialog1.Filter = "All Type Of Image Files|*.*|Joint Photographic Experts Group [JPEG]|*.jpg|Bitmap [BMP|*.bmp|Tagged Image File Format [TIFF]|*.tiff|Portable Network Graphics [PNG]|*.png"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
ProgressBar2.Show()
ProgressBar2.Step = 10
Dim str As String
For Each str In OpenFileDialog1.FileNames
Load.Text = "Loading..."
Dim fso As New FileSystemObject
Dim MyName As String
Dim MyExtension As String
MyName = fso.GetFileName(CStr(str))
MyExtension = fso.GetExtensionName(MyName)
System.IO.File.Copy(str, Application.StartupPath + "\Backup\" + MyName & "." & MyExtension, True)
CheckedListBox1.Items.Add(str, CheckState.Checked)
Thumbcontrol1.AddThumbnail(str)
Thumbcontrol1.BackgroundImage = Nothing
CheckedListBox1.SelectedIndex = 0
ProgressBar2.PerformStep()
Next
SaveProject.Enabled = True
Delete.Enabled = True
Edit.Enabled = True
ClearAll.Enabled = True
CheckAll.Enabled = True
UncheckAll.Enabled = True
Timer1.Stop()
Load.Text = "Loading Completed"
Else
End If
ProgressBar2.Visible = False
Load.Text = Nothing
End Sub
Remove ProgressBar2.Step = 10 line and do this:
Dim str As String
Dim counter As Integer 'new!
For Each str In OpenFileDialog1.FileNames
Load.Text = "Loading..."
Dim fso As New FileSystemObject
Dim MyName As String
Dim MyExtension As String
MyName = fso.GetFileName(CStr(str))
MyExtension = fso.GetExtensionName(MyName)
System.IO.File.Copy(str, Application.StartupPath + "\Backup\" + MyName & "." & MyExtension, True)
CheckedListBox1.Items.Add(str, CheckState.Checked)
Thumbcontrol1.AddThumbnail(str)
Thumbcontrol1.BackgroundImage = Nothing
counter += 1 'new
CheckedListBox1.SelectedIndex = 0
ProgressBar2.Value = (counter * 100) / OpenFileDialog1.FileNames.Length 'new
Next
It does not address the problem of your not using threading, as other answers are correct to point out.
Don´t use the UI for loading. Use Background worker. BackgroundWorker works in another thread, and it can report the progress to bind it to a progressbar.
The progress bar stops moving because Windows thinks there is something seriously wrong with your program. It replaces your main window with the 'ghost' window, you can tell because it says "Not Responding" in the title bar.
It does this to help alert the user that your program is dead to the world and will not respond to any input from the user. Clicking the mouse or banging on the keyboard will not have any effect, all the user can do is watch helplessly while your code goes through the motions.
This does not make a desirable user interface. You solve it by using BackgroundWorker so the heavy lifting is done on a separate thread. Leaving the user interface thread responsive. Be sure to read the MSDN article for it so you know what to do, you'll have to adapt your code.