Building an Electronic Clock in VB.Net using timer class

April 27, 2008 by vbadud

Using Timer in VB.Net


Building an Electronic Clock in VB.Net using timer class

(VB.NET ProgressBar using Timer)

Public Class Form1

Dim t As New Timer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

t.Interval = 1000

AddHandler t.Tick, AddressOf Me.t_ShowProgress

AddHandler t.Tick, AddressOf Me.t_ShowTime

t.Start()

End Sub

Private Sub t_ShowProgress()

ProgressBar1.Value += 10

If ProgressBar1.Value = 100 Then

ProgressBar1.Value = 0

End If

End Sub

Private Sub t_ShowTime()

Label1.Text = Now

End Sub

End Class

Add Handler – Associates an event with an event handler at run time. The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles keyword when defining a procedure to specify that it handles a particular event.

The Tick event (this is similar to Visual Basic Timer1_Timer event) occurs when the specified timer interval has elapsed and the timer is enabled. This is based on the interval set for the Timer (1000 ms or 1 sec here)

The progress bar will be reset after it reaches 100. The timer will run till the form is closed. Since the process is synchronous only the timer event will be executed or the label will be updated. The same can also be achieved async

Regular Expressions in Dot Net (.NET)

Finding Duplicate Words in a String using .NET Regular Expressions

Regular Expressions (REGEX) does wonders in programming. Here is a simple Regex code that identifies duplicate words like ‘the the’, ’something something’ etc. Probably copyeditors can use this code to do the work that Microsoft Spell check does

Sub Regex_Checker_Duplicate_Words()

Dim oRegex As Regex

Dim sPattern As String

Dim oMatches As Match

Dim sText As String

sText = ” the the category catastropic cat cat and rat b b “

sPattern = “\b([a-zA-Z]+)\s+\1″

oRegex = New Regex(sPattern)

oMatches = oRegex.Match(sText, sPattern)

While oMatches.Success

MsgBox(oMatches.Groups(0).Value.ToString)

oMatches = oMatches.NextMatch

End While

End Sub

Returns a new Match with the results for the next match, starting at the position at which the last match ended (at the character beyond the last matched character).

Get Computer Name in .Net

December 25, 2007 by vbadud

Get Computer Name in .Net

Use the My object to get the name of the computer

‘ Returns Name of the Computer

Function Get_Comp_Name() As String

Return My.Computer.Name.ToString

End Function

The VBA/Visual Basic function to do the same is :
http://vbadud.blogspot.com/2007/05/get-computer-name.html

The SQL Statement to get the computer name is :
http://sqldud.blogspot.com/2007/04/get-computer-name-from-sql-query.html

Changing LINKS

ASP.Net Get User / .Net Get User

December 25, 2007 by vbadud

ASP.Net Get User / .Net Get User

User names are the most important ones. Whether to write in logs or display a warm hello message, it is there throughout

Here let us look at the way to get the user of the system. Webdevelopemt will have different ‘users’.

Function Get_User_Name() As String

Return My.User.Name

End Function

BlogRankings.com

Again the My namespace comes in handy

The same can be done using VBA :
http://vbadud.blogspot.com/2007/05/get-computer-name.html

For knowing the user using SQL select statement please refer :

Opening & Closing Forms in .Net

December 25, 2007 by vbadud

Opening & Closing Forms in .Net

Opening & Closing the forms have changed from Visual Basic 6.0 to VB.Net

The Form object in Visual Basic 6.0 is replaced by the Form class in Visual Basic 2005. The names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior

Form1.Show Modal=True in VB 6.0 is replaced with the ShowDialog

Sub Show_Form_Modal()

Form1.ShowDialog() ' Modal

End Sub

Sub Show_Form_Modeless()

Form1.Show() ' Modeless

End Sub

Closing which was done by Unload(Me)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.Close()

End Sub

Top Computers blogs

VB.Net Form Close vs Form Dispose

December 25, 2007 by vbadud

VB.Net Form Close vs Form Dispose

Two methods doing some identical jobs always create some confusion. What to use to ‘unload’ the form Form.Close or Form.Dispose

Form.Close should be the answer as going by Microsoft Form.Close disposes the form as well if the form Modeless .

One more advantage you get from this method is from the events that are associated with the form

You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If MessageBox.Show(“Form is closing”, “Form Close”, MessageBoxButtons.YesNo, MessageBoxIcon.Hand) = Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub

The above prevents the form being closed

When the form is opened as Modal form (using Showdialog) you can dispose the form explicitly


Setting Default & Cancel Buttons in Visual Basic.Net Form

December 25, 2007 by vbadud

VB.Net Setting Default & Cancel Buttons

Setting Default & Cancel Buttons in Visual Basic.Net Form

Default button is in VB.NEt with a different name – AcceptButton. However, cancel button retains its name:

Here is a way you can set them

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

‘Sets cmdOK as the button control that is clicked when the user presses the Enter key.
Me.AcceptButton = cmdOK

‘Sets cmdCancel as the button control that is clicked when the user presses the ESC key.
Me.CancelButton = cmdCancel

End Sub

For setting the same in VBA/VB refer : http://vbadud.blogspot.com/2007/06/setting-default-cancel-buttons-in.html

Get Folder Size using .Net

December 25, 2007 by vbadud

Directory Size using VB.Net

For getting the size of each directory in Vb.Net, you need to add up the size of each file in the directory.

This function gets the size of each directory including sub-directories and writes to a text file

Imports System.IO

Dim oBuffer As System.IO.TextWriter

Function Get_Directory_Size(ByVal sDirPath As String)

Dim lDirSize As Long
Dim oDir As DirectoryInfo
Dim sDir As DirectoryInfo
Dim sFiles As FileInfo
Dim iFN As Short ‘* File Number
Dim sPath As String ‘* Saving Path

‘Dim oFSW As System.IO.FileSystemWatcher

oDir = New DirectoryInfo(sDirPath)

Dim oDirs As DirectoryInfo() = oDir.GetDirectories()

For Each sDir In oDirs

lDirSize = 0

For Each sFiles In sDir.GetFiles(“*.*”)
lDirSize += sFiles.Length
Next

‘——————————————————–
‘ Coded by Shasur for http://dotnetdud.blogspot.com/
‘——————————————————–

‘MsgBox(“Size of Directory ” & sDir.Name & ” is ” & lDirSize)
oBuffer.WriteLine(sDir.FullName & vbTab & lDirSize)

Get_Directory_Size(sDirPath & sDir.Name & “\”)

Next

End Function

The procedure below uses WriteLine function of the StreamWriter class

Sub Store_Size_Of_Directory

Dim sOPFile As String

sOPFile = c:\SystemDirSize.log”

‘——————————————————–
‘ Coded by Shasur for http://dotnetdud.blogspot.com/
‘——————————————————–

oBuffer = New System.IO.StreamWriter(sOPFile)
oBuffer.WriteLine(Now())

Get_Directory_Size(“c:\”)

oBuffer.Close()
End Sub

Directory Selection in Windows Forms using VB.Net

December 25, 2007 by vbadud

Selecting a Folder in VB.Net

The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in Visual Basic 2005. If you want to select a directory FolderBrowser Dialog will be the one you need to use

For this example, Let us have a form with a TextBox and a command button. When the command buton is pressed, the folderdialog is shown and then the selected folder is displayed in the textbox

Sample Form:

Add the FolderBrowser Dialog to the form from the Dialogs Collection (see below).

This control will not be placed on the form but on a separate tray at the bottom of the Windows Forms Designer. (see below)

Now in the click event for the Button have the following code:

Private Sub BtnFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFolder.Click

Dim MyFolderBrowser As New System.Windows.Forms.FolderBrowserDialog

‘ Descriptive text displayed above the tree view control in the dialog box
MyFolderBrowser.Description = “Select the Folder”

‘ Sets the root folder where the browsing starts from
‘MyFolderBrowser.RootFolder = Environment.SpecialFolder.MyDocuments

‘ Do not show the button for new folder
MyFolderBrowser.ShowNewFolderButton = False

Dim dlgResult As DialogResult = MyFolderBrowser.ShowDialog()

If dlgResult = Windows.Forms.DialogResult.OK Then
txt_watchpath.Text = MyFolderBrowser.SelectedPath
End If

End Sub

The FolderBrowserDialog component is displayed at run time using the ShowDialog method. Set the RootFolder property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. Once the dialog box has been shown, you can use the SelectedPath property to get the path of the folder that was selected

For similar functionality in VB6.0 refer http://vbadud.blogspot.com/2007/04/browse-folder-select-folder-thru-shell.html

When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility).

OpenFileDialog in Visual Basic .Net

December 25, 2007 by vbadud

OpenFileDialog in Visual Basic .Net

List Files in Visual Basic .Net / Visual Basic 2005

The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in Visual Basic 2005.

Conceptual Differences
The Visual Basic 6.0 DirListBox control was typically used to display directories and paths in a File Open or Save dialog box.

In Visual Basic 2005, the Windows Forms OpenFileDialog and SaveFileDialog components provide the ability to create standard Windows dialog boxes for working with files, in most cases eliminating the need for the DirListBox control.

For this example, Let us have a form with a TextBox and a command button. When the command buton is pressed, the folderdialog is shown and then the selected folder is displayed in the textbox

Sample Form:

Add the FolderBrowser Dialog to the form from the Dialogs Collection (see below).

This control will not be placed on the form but on a separate tray at the bottom of the Windows Forms Designer. (see below)

Now in the click event for the Button have the following code:

Private Sub BtnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFile.Click

Dim MyFileOpen As New System.Windows.Forms.OpenFileDialog
Dim bExOccured As Boolean
Dim retVal As DialogResult
Dim sMyFile As String
Try
‘ does not add an extension to a file name if the user omits the extension
MyFileOpen.AddExtension = True

‘dialog box does not allow multiple files to be selected
MyFileOpen.Multiselect = False

MyFileOpen.Filter = “ASCII files (*.txt;*.log)|*.txt;*.log”

retVal = MyFileOpen.ShowDialog()
If retVal = Windows.Forms.DialogResult.OK Then

If MyFileOpen.CheckFileExists = True And MyFileOpen.CheckPathExists = True Then

sMyFile = MyFileOpen.FileName

End If
End If
Catch ex1 As AccessViolationException
MsgBox(ex1.StackTrace.ToString)
bExOccured = True
Catch ex As Exception
MsgBox(ex.StackTrace.ToString)
bExOccured = True
Finally
If bExOccured = True Then
MsgBox(“Program executed with some errors!!!”)
End If
End Try
End Sub

You can use filters to restrict the type of files that can be opened. A sample of common filters is given below

‘MyFileOpen.Filter = “Microsoft Word Documents (*.doc)|*.doc|Microsoft Word Documents (*.rtf)|*.rtf”
‘MyFileOpen.Filter = “Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF”
‘MyFileOpen.Filter = “Microsoft Word Documents (*.doc;*.rtf)|*.doc;*.rtf”

‘MyFileOpen.Filter = “Microsoft Excel Workbooks (*.xls)|*.xls”
‘MyFileOpen.Filter = “Microsoft Excel Addins (*.xla;*.xll)|*.xla;*.xll”
‘MyFileOpen.Filter = “All files (*.*)|*.*”
‘MyFileOpen.Filter = “Text files (*.txt)|*.txt”

This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only check box is checked.

Most of the functionality for this class is found in the FileDialog class.

Microsoft recommends that you use the OpenFileDialog and SaveFileDialog components to provide a consistent and familiar user experience. If you find it necessary to create your own file dialog boxes, Visual Basic 2005 does provide a DirListBox control as part of the Microsoft Visual Basic Compatibility Runtime library.

For CommonDialog implementation in VB6.0 refer http://vbadud.blogspot.com/2007/06/visual-basic-common-dialog.html

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility).

Opening & Closing of Application using .Net / Create New process in .Net / Shell Function in .Net

December 25, 2007 by vbadud

Opening & Closing Notepad using .Net

A program is not Userinterface and database connections alone, it also needs to interact with other applications. Many a times, this interaction happens internally, like updating Word Template, Printing out a document etc, but there are times where one needs to open an document through the Application.

Let us have a sample app that opens a Notepad on click of a command button. We have a sample form with a button (see below).

Now add the process control from the Components Control (see below)

This control has no design features and will be used in run-time and it straightway gets docked in the tray (see below)

Change the following properties of the control.

This can also be changed during run time.

Now in the Button Click event write the following code:

Private Sub ButtonNotepad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadNotepadButton.Click
‘ http://dotnetdud.blogspot.com/
ProcessNotepad.EnableRaisingEvents = True
ProcessNotepad.Start()

End Sub

The EnableRaisingEvents property indicates whether the component should be notified when the operating system has shut down a process. The EnableRaisingEvents property is used in asynchronous processing to notify your application that a process has exited. To force your application to synchronously wait for an exit event (which interrupts processing of the application until the exit event has occurred), use the WaitForExit method.

This will start the Notepad Application. If you want receive the closure of application use the following event

Private Sub ProcessNotepad_Exited(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessNotepad.Exited
‘ Coded for http://dotnetdud.blogspot.com/
MessageBox.Show(“Notepad has been closed “, “Dot Net Tips & Tricks”, MessageBoxButtons.OK)
End Sub

If you want to close the application use the kill method.

Private Sub ButtonClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeNotepadButton.Click
If ProcessNotepad.HasExited = False Then
ProcessNotepad.Kill()
End If
End Sub

We have used Notepad, as it is simple and easy. Try it with other stuff!!

Cheers
Shasur