65.9K
CodeProject is changing. Read more.
Home

Custom Message Box Using Thread That Closes Automatically

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

May 23, 2013

CPOL

1 min read

viewsIcon

18390

downloadIcon

305

Implimenting a message box that closes automatically using thread.

Introduction

This is a simple article on making a custom dialog box to show a message to an application user. A dialog box that can be set to close automatically itself, which is implemented using a thread.

This article does not deal with Threading in depth. But a simple idea of using a thread can be taken.

Background

This is the result of a task where I have to:

  • Avoid the use of VB.NET msgbox() function and make custom form to give info to user
  • Form that can be set to closed automatically after some time
  • Give unique look on all info to user over the project

Using the code

The form customMsgBox.vb is implemented with:

Public Class customMsgBox

    Private infoTitle, infoMessage As String
    Private infoWidth As Integer = 420
    Private infoHeight As Integer = 190
    Private AutoClose As Boolean = False
    Private waitTime As Integer  
 
    Public Sub New(ByVal Title As String, ByVal Message As String, _
                   ByVal isAutoClose As Boolean, ByVal duration As Integer)

        InitializeComponent()  ' This call is required by the Windows Form Designer.

        infoTitle = Title
        infoMessage = Message
        AutoClose = isAutoClose
        waitTime = duration

End Sub 

The main part of the customMsgBox load event is to check the AutoClose boolean and process as:

If AutoClose Then  'if autoclose then start thread
    Dim mthread As New Threading.Thread(AddressOf waitNclose)
    mthread.Start()
End If

Here waitNclose is a sub that waits till the time defined and closes the form customMsgBox. Since waitNclose is run in a different thread, we can not access customMsgBox and its properties inside waitNclose. So the customMsgBox.close operation is implemented by calling another sub closeform.

Private Sub waitNclose()
    System.Threading.Thread.Sleep(waitTime * 1000) 'wait time
    closeform(True)
End Sub

Private Sub closeform(ByVal closeOrNot As Boolean)
    If Me.InvokeRequired Then
        Me.Invoke(New Action(Of Boolean)(AddressOf closeform), closeOrNot)
Else
          Me.Close()
   End If
End Sub 

Using the customMsgBox inside frmmain.vb:

Dim myTitle, myMsg As String
Dim isAuto As Boolean
Dim waitTime As Integer

waitTime = Me.txtWait.Text
myTitle = Me.txtTitle.Text
myMsg = Me.rtbMsg.Text
isAuto = Me.txtWait.Text

Dim myMsgBox As New customMsgBox(myTitle, myMsg, isAuto, waitTime)
myMsgBox.Show() 

Points of Interest 

This is a simple article on using your own dialog box. It uses threads with a minimal approach. Hence it is targeted at beginners.

History

Download link updated.