Monday, April 1, 2013

Using Threads in VB.Net for showing a progress bar in a separate dialog

I am new to VB.NET. I had programmed in Visual Basic 4 many many years ago. Recently I had to use Visual Studio 2010 to create a quick application for internal usage. Now there was a task which took a long time. As per good user interface design it was obvious that a progress update should be shown to keep the end user informed and updated till the task completed.

To cut a long story short, the requirement was to let the long running task continue while a progress bar showed the progress of the task. After searching for examples, I got a basic idea on how to use threads in VB.Net to accomplish the task I had at hand. 

Fig. 1 Main Dialog


 
  Fig. 2 Separately Launched Progress Dialog

I have attached the VS2010 project for you to download and see the code. The main working parts are explained here.

Basic Steps
  • Step 1 - Create a basic Windows Form application
  • Step 2 - Create a simple Dialog and add a ProgressBar and a Label to it
  • Step 3 - Write a method which will launch a separate Thread to perform the long running task
  • Step 4 - Write Delegate methods in the Dialog

The code is self explanatory.

Code for the Main Form

Option Explicit On
Option Strict On

Imports System.Threading

' Main form which launches a long running task and 
' shows progress update in a separate dialog
Public Class MainForm
    Inherits Form

    'Flag that indcates if a process is running
    Dim isProcessRunning As Boolean = False

    'Progress bar dialog
    Dim progressDlg As New ProgressDialog


    'Long running background process with 
    'a determinate progress indicator, 
    'using a seperate modal dialog containing
    'a progress bar

    <MTAThread()> _
    Private Sub ButtonClick1_Click(ByVal sender As System.Object, _
                                   ByVal e As System.EventArgs) _
                               Handles ButtonClick1.Click

        'If a process is already running, 
        'warn the user and cancel the operation
        If isProcessRunning = True Then
            MessageBox.Show("Sorry, a process is already running.", _
                            "Status", MessageBoxButtons.OK, _
                            MessageBoxIcon.Exclamation)
            Return
        End If

        'Define a background thread and start the 
        'long running process in this separate thread
        Dim backgroundThread As _
            New Threading.Thread(AddressOf DoLongRunningProcess)

        ' Start the background process thread
        backgroundThread.Start()

        ' Open the dialog
        progressDlg.Show()
    
End Sub

     
    ' The long running process 

    Public Sub DoLongRunningProcess()
        ' Set the flag that indicates if a 
        ' process is currently running
        isProcessRunning = True
        
        ' Iterate from 0 - 100
        ' On each iteration, pause the thread 
        ' for .05 seconds, then update the 
        ' dialog's progress bar
        For n As Integer = 0 To 100
            Thread.Sleep(100)
            progressDlg.UpdateProgress(n)
        Next
        
        ' Show a dialog box that confirms the process 
        ' has completed
        MessageBox.Show("Thread completed!", "Status", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Information)
        'Close the dialog when user clicks OK
        progressDlg.Close()
        ' Reset the flag that indicates if a process is
        ' currently running
        isProcessRunning = False
    End Sub
  
End Class
Code for the Progress Dialog
Option Explicit On
Option Strict On
Imports System.Windows.Forms
  
' Dialog class with a ProgressBar widget to 
' show the progress of a long running task
 
Public Class ProgressDialog
    Inherits Form

    ' Delegate to update the progress 
    ' of the ProgressBar widget
    Delegate Sub DelegateUpdate(ByVal progress As Integer)
   
    ' Delegate to handle the Close event 
    ' for this dialog
    Delegate Sub DelegateClose(ByRef dialog As Form)

    ' Default constructor which initializes 
    ' this control
    Public Sub New()
        InitializeComponent()
    End Sub


    
    ' Method to update the progress bar widget. This 
    ' uses the InvokeRequired and BeginInvoke methods
    Public Sub UpdateProgress(ByVal progress As Integer)
        If ProgressBar1.InvokeRequired Then
            ProgressBar1.BeginInvoke(New DelegateUpdate(AddressOf UpdateDelegateImpl), progress)
        Else
            ProgressBar1.Value = progress
        End If
    End Sub

    ' Overloads the Close method
    Public Overloads Sub Close()
        If Me.InvokeRequired Then
            Me.BeginInvoke(New  _
                           DelegateClose(AddressOf CloseDelegateImpl), Me)
        Else
            Me.Close()
        End If
    End Sub
   
    ' Implementation of the DelegateUpdate
    Sub UpdateDelegateImpl(ByVal progress As Integer)
        ProgressBar1.Value = progress
        LabelProgress.Text = ""
        LabelProgress.Text = progress & CStr("%")
    End Sub
    
    ' Implmentation of the DelegateClose
    Sub CloseDelegateImpl(ByRef dialog As Form)
        dialog.Close()
    End Sub

End Class

Download Project
I have uploaded the project as a ZIP archive on Google Drive. Click to download.

Friday, January 21, 2011

Quickly and selectively clean up your Internet Explorer cache

While testing GWT applications it is sometimes necessary to clean up your entire cache. Firefox has simple shortcut keys to achieve this, but IE does not. Especially IE7. (Yes we have to support IE7 as the lowest version)

Here is a quick way to do it. You can run this from a command prompt, or a batch file or simply from the 'Run' menu which pops up when you click Run from the Start menu.

#To clear IE7 temporary Internet files
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

#To clear IE7 browsing cookies
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

#To clear IE7 browsing history
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

#To clear IE7 form data
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

#To clear IE7 remembered passwords for filling web login forms
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

#To clear or delete all IE7 browsing history i.e all of the above!
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255


Wednesday, October 7, 2009

Testing Windows Live Writer to post to my blog

Just testing how Windows Live Writer works to post directly to my blog. Apparently it works just fine :)

Tuesday, June 23, 2009

Looking at BlackBerry as a development platform

I found an interesting article about experiences of developing for the BlackBerry.

Thursday, June 11, 2009

Should I take the plunge into iPhone development?

I have been delaying getting into iPhone Application development. I had so many ideas for developing applications for the mobile device. Android definitely helped me get a feel of what it takes to develop mobile apps. My last experience developing for a hand held device was with Palm OS 3.0 with Code Warrior IDE about a decade ago. After that Android has been my only foray into mobile development.

The reason I feel that I should finally give in to iPhone is that I dont see much traction for Android applications. The market place and success stories of iPhone developers lure me more towards it. The other reason is that I want to keep my skills current and relevant. When Palm Pre was to be released there was much excitement in the developer community, but now it seems to have fizzled out.

I want to be able to learn an exciting new platform and also look at it in a slightly commerical light. Why should I not be able to translate my efforts to dollars?

My biggest mental block to iPhone is perhaps the requirements where I have to get a Mac. I have always been a developer who has used Windows and Linux to quite an extent. I have only used a Mac for maybe an hour or so in my entire career.

Or should I look into Symbian? It has a Windows based development environment.

Anyone out there who has some experience with this? Please share your thoughts.

Wednesday, December 17, 2008

Android SendMail - Send Email Programmatically

SendMail is really an excellent email program found on most Unix systems. I just borrowed the name for my tutorial on sending email programmatically from an Android phone.
Long ago, when I worked on the Palm OS, one could create an email message programmatically, and then place it in the Outbox of the Email application. Once the PDA was synced with the PC, the email would be sent. I was looking for a similar way to send email from the Android phone. After searching the google groups and scouring websites and android docs, I managed to piece together a simple example.

Saturday, November 1, 2008

Tipster on the real Android G phone

I finally got a chance to run the Tipster application on a real Android powered T-Mobile G phone. I realised that you have to slide open the keyboard to enter values, thus changing the view into a 'landscape mode'. When you do that, the results of the tip calculations are not visible as they are towards the bottom half of the screen. So I experimented and found that I needed to allow 'scrolling' of the view. I have updated the the tutorial with the simple enhancements to make the application visible even in landscape mode.