1 2 3 4 5  ... Previous Next 

Numeric textbox for Windows Forms


Often is asked about a numeric textbox. This code does that and checks if as well if there is no numerics are pasted. Be aware you can add to check for decimail points in the way as you wish.
Public Class Form1
    Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgsHandles TextBox1.KeyPress
        If Not Char.IsDigit(CChar(e.KeyChar)) AndAlso Not {ControlChars.Back}.Contains(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub
    'For paste protection
    Private Sub TextBox1_Leave(sender As Object, e As EventArgsHandles TextBox1.Leave
        For i = 0 To TextBox1.Text.Length - 1
            Dim x As Char = CChar(TextBox1.Text(i))
            If Not Char.IsDigit(CChar(TextBox1.Text(i))) Then
                MessageBox.Show("TextBox contains not allowed characters")
                TextBox1.Focus()
            End If
        Next
    End Sub
End Class



Windows .Net MediaPlayer playing in windows forms


.Net contains a nice player to play MP3 files. A pity is that it is until now not so well documented on MSDN. Here the most simple format to let an MP3 file play in windows forms.
'Add a reference to presenationcore and WindowsBase
Imports System.Windows.Media
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgsHandles MyBase.Load
        Dim MPlayer As New MediaPlayer
        MPlayer.Open(New System.Uri("C:\Test\test.MP3"))
        MPlayer.Play()
    End Sub
End Class



Set a key in the registry which expires after 15 days


This is just a sample how it can be done. Don't think expirienced users cannot hack it, they can.

It is only to give you an idea.


Untitled 1

Imports Microsoft.Win32

Imports System.Security

Imports System.Security.Cryptography

Imports System.Text

Public Class Form1

    //VB2010 SP1 code, so no byval's

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load

        Dim rk As RegistryKey = Registry.Users

        Dim keyName = "HKEY_CURRENT_USER\ExpireExample"

        Dim registeredDate As Object = Registry.GetValue(keyName, "Abacadabra""Empty")

 

        If registeredDate Is Nothing OrElse registeredDate.ToString = "Empty" Then

            registeredDate = Now.ToShortDateString

            Registry.SetValue(keyName, "Abacadabra", Encrypt(registeredDate.ToString))

        Else

            registeredDate = DeCrypt(registeredDate.ToString)

        End If

        Dim expirationDate = CDate(registeredDate).AddDays(15) 'to adjust it use this key

        If expirationDate < Now Then MessageBox.Show("Expired")

    End Sub

    Private Function Encrypt(Source As StringAs String

        Dim desCrypto As New TripleDESCryptoServiceProvider

        Dim hashMD5 As New MD5CryptoServiceProvider()

        Dim byteHash As Byte()

        Dim byteBuff As Byte()

        byteHash = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes("Donkey"))

        desCrypto.Key = byteHash

        desCrypto.Mode = CipherMode.ECB

        byteBuff = ASCIIEncoding.ASCII.GetBytes(Source)

        Return Convert.ToBase64String(desCrypto.CreateEncryptor().

   TransformFinalBlock(byteBuff, 0, byteBuff.Length))

    End Function

    Private Function DeCrypt(Source As StringAs String

        Dim desCrypto As New TripleDESCryptoServiceProvider

        Dim hashMD5 As New MD5CryptoServiceProvider()

        Dim byteHash As Byte()

        Dim byteBuff As Byte()

        byteHash = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes("Donkey"))

        desCrypto.Key = byteHash

        desCrypto.Mode = CipherMode.ECB

        byteBuff = Convert.FromBase64String(Source)

        Return ASCIIEncoding.ASCII.GetString(desCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length))

    End Function

End Class

 




Scheduler with a dataforms DataGridView and a dataset writeXML


In the forums is often the question "How can I make a scheduler, one of the good answers is, use the inbuild scheduler of the OS.
However, it is also a good learning practise to try to make it yourself.
Therefore we have created a simple sample for that scheduler here.
It needs only a label with beneath that a datetimepicer and a DataGridView on a Windows Forms form
Public Class Form1
    'SP10SP1 style code
    Private WithEvents Tm As New Timer With {.Enabled = False, .Interval = 3000}
    'Be aware that 3 seconds is to short
    Private DS As New DataSet
    Private Sub Form1_Load(sender As Object, e As System.EventArgsHandles Me.Load
        DateTimePicker1.Format = DateTimePickerFormat.Time
        Label1.Text = Now.ToLongDateString
        If IO.File.Exists(IO.Path.Combine(CStr(Environment.SpecialFolder.ApplicationData),
                                          Me.CompanyName, "Scheduler.xlm")) Then
            DS.ReadXml(IO.Path.Combine(CStr(Environment.SpecialFolder.ApplicationData),
                                       Me.CompanyName, "Scheduler.xlm"))
            Tm.Enabled = True
        Else
            DS.Tables.Add(New DataTable("Schedule"))
            DS.Tables(0).Columns.Add(New DataColumn("Appointment"))
            IO.Directory.CreateDirectory(IO.Path.Combine(CStr(Environment.
                                                         SpecialFolder.ApplicationData), Me.CompanyName))
        End If
        'Set the appointments in order of appointment
        DS.Tables(0).DefaultView.Sort = "Appointment"
        DataGridView1.DataSource = DS.Tables(0).DefaultView
        'Next appointment
        DS.Tables(0).DefaultView.RowFilter = "Appointment > '" & CStr(Now) & "'"
        If DS.Tables(0).DefaultView.Count > 0 Then
            TextBox1.Text = CStr(DS.Tables(0).DefaultView(0)(0))
        End If
    End Sub
    Private Sub Button1_Click(sender As System.Object, e As System.
                              EventArgsHandles Button1.Click
        Dim nr As DataRow = DS.Tables(0).NewRow
        nr(0) = DateTimePicker1.Value
        DS.Tables(0).Rows.Add(nr)
        Tm.Enabled = True
    End Sub
    Private Sub Tm_Tick(sender As Object, e As System.EventArgsHandles Tm.Tick
        If DS.Tables(0).DefaultView.Count > 0 Then
            If CDate(DS.Tables(0).DefaultView(0)(0)) < Now.
                AddSeconds(4) And CDate(DS.Tables(0).DefaultView(0)(0)) > Now.AddSeconds(-3) Then
                MessageBox.Show("You Have an appointment")
            End If
            DS.Tables(0).DefaultView.RowFilter = "Appointment > '" & CStr(Now) & "'"
        End If
    End Sub
    Private Sub Form1_FormClosing(sender As Object,
                                  e As System.Windows.Forms.FormClosingEventArgsHandles Me.FormClosing
        DS.WriteXml(IO.Path.Combine(CStr(Environment.SpecialFolder.ApplicationData), Me.CompanyName, "Scheduler.xlm"))
    End Sub
End Class



A list of classes with Linq and set in a Listbox without a datasource but 2 values


A sample how to create a table with a generic List, to put that in a Listbox, and to use the items by Linq to fill the textboxes based on the changes of the Listbox

Untitled 3
Public Class Form1
    'sample in VB10 SP1 style for older versions add byval
    Private Countries As New List(Of Country)
    Private Sub Form1_Load(sender As Object,
                           e As System.EventArgsHandles Me.Load
        Countries.Add(New Country With {
                      .Abbreviation = "USA",
                      .FullName = "United States of America",
                      .Continent = "America"})
        Countries.Add(New Country With {
                      .Abbreviation = "EU",
                      .FullName = "European Union",
                      .Continent = "Europe"})
        For Each ctry In Countries
            ListBox1.Items.Add(ctry.Abbreviation)
        Next
    End Sub
 
    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object,
                                              e As System.EventArgs
                                              ) Handles ListBox1.SelectedIndexChanged
        Dim cntr = (From ctr In Countries Where
                    ctr.Abbreviation = CStr(ListBox1.SelectedItem)).First
        TextBox1.Text = cntr.FullName
        TextBox2.Text = cntr.Continent
    End Sub
End Class
Public Class Country
    Public Property Abbreviation As String
    Public Property FullName As String
    Public Property Continent As String
End Class 



1 2 3 4 5  ... Previous Next