How to create a screen saver by using Visual Basic .NET or Visual Basic 2005

Article translations Article translations
Article ID: 818359 - View products that this article applies to.
Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article describes how to create a screen saver by using Microsoft Visual Basic .NET or Microsoft Visual Basic 2005. You can develop a marquee screen saver with a configuration form. You can build, you can test, and you can register the screen saver in the \Windows directory.

Create the Screen Saver Project

  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Windows Application under Templates.

    Note In Visual Studio 2005, click Visual Basic under Project Types.
  4. Name the project MyScreenSaver, and then click OK.

    By default, Form1 is created.
  5. Set the properties of Form1 as follows:
    • Name: frmscr
    • ControlBox: False
    • MaximizeBox: False
    • MinimizeBox: False
    • BackColor: Black
    • Text: ""(no text)
    • TopMost: True
    • WindowState: Maximized
  6. In the Solution Explorer window, right-click Form1, and then click Properties.
  7. In the File Properties window, set the File Name property to frmscr.vb.
  8. Add a Label control.

    By default, Label1 is added to the form.
  9. Set the properties of Label1 as follows:
    • Name: lblMessage
    • ForeColor: Yellow
  10. Add a Timer control.

    Timer1 is added to the form.
  11. Set the Enabled property of the timer to True.
  12. To disable the CTRL+ALT+DEL key combination on a Microsoft Windows 95 operating system or on a Microsoft Windows 98 operating system, and to obtain the user's previous preference for the marquee text, add the following code to the load event of the frmscr form:
     
      Dim tmpLng As Integer
            tmplng = SystemParametersInfo(SPI_SCREENSAVERRUNNING, 1&, 0&, 0&)
    
            Dim pRegKey As RegistryKey = Registry.CurrentUser
            pRegKey = pRegKey.OpenSubKey("Software\Test Screen Saver", True)
            Dim val As Object = pRegKey.GetValue("Message", "Enter Text here")
            pRegKey.Close()
            lblMessage.Text = val.ToString
    
            Me.Cursor.Current.Hide()
      
    The Cursor.Current.Hide() method makes the cursor disappear when the screen saver is displayed.
  13. To close the screen saver when you press any key, add the following code to the KeyDown event of the frmscr form:
    'Immediately end when any key is pressed.
            Me.Close()
    
  14. To close the screen saver when you move the mouse, add the following code to the MouseMove event of the frmscr form:
     
            Static OldX As Integer
            Static OldY As Integer
    
            'Determines whether the mouse was moved and whether the movement was large.
            'If so, the screen saver is ended.
            If (OldX > 0 And OldY > 0) And (Abs(e.X - OldX) > 3 Or Abs(e.Y - OldY) > 3) Then
                Me.Close()
    
            End If
            'Assigns the current X and Y locations to OldX and OldY.
            OldX = e.X
            OldY = e.Y
    
  15. To restore the cursor while you close the screen saver and to re-enable the CTRL+ALT+DEL key combination, add the following code in the Closing event of the frmscr form:
    'Restore the mouse cursor.
            Dim tmplng As Integer
            Me.Cursor.Current.Show()
    
           'Re-enable the CTRL+ALT+DEL key combination if it is disabled.
            tmplng = SystemParametersInfo(SPI_SCREENSAVERRUNNING, 0&, 0&, 0&)
    
  16. To provide a marquee effect, add the following code to the Tick event of the Timer control:
    'Determine whether the Message has moved completely off the left side of the screen.
            If lblMessage.Left < (0 - lblMessage.Width) Then
                lblMessage.Left = GetScaleWidth(Me) 'ScaleWidth
            End If
    
            'Moves lblMessage to the left.
            lblMessage.Left = lblMessage.Left - 10
    
  17. On the Project menu, click Add Module.

    By default, Module1 is created.
  18. To display the user configuration form or the screen saver form (based on the Windows command-line arguments), add the following Sub Main event to Module1:
    Public Sub Main(ByVal args As String())
            Dim Inst As Boolean = False
    
            If args.Length > 0 Then
                sStartType = args(0).ToLower.Trim().Substring(0, 2)
    
                If sStartType = "" Then
                    'This will occur when a user right-clicks the .scr
                    'file and then selects "configure"
                    sStartType = "/c"
                End If
    
                ' Determine whether the screen saver should show user definable options.
                If sStartType = "/c" Then
                    Dim usercnfg As New frmcnfg
                    usercnfg.ShowDialog()
    
                    ' Exit the application.
                    Exit Sub
                End If
    
                ' Determine whether the screen saver should just execute.
                If sStartType = "/s" Then
                    'Check for previous instance.
                    Inst = PrevInstance()
                    If Not (Inst) Then
                        ' Create a Screen Saver form, and then display the form.
                        Dim scrsvr As New frmscr
                        scrsvr.ShowDialog()
                    Else
                        'If a previous instance exists, exit the application.
                        Exit Sub
                    End If
                End If
            End If
     End Sub 
    
    The PrevInstance() function determines whether a previous instance of the screen saver is running.
  19. To determine whether a previous instance of the screen saver is running, add the PrevInstance() function to Module1 as follows:
    Function PrevInstance() As Boolean
            If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
                Return True
            Else
                Return False
            End If
    End Function

Add the Screen Saver Setup Form

  1. On the Project menu, click Add Windows Form.
  2. In the Add New Item dialog box, click Windows Form under Templates.
  3. Type frmcnfg in the Name text box, and then click Open.
  4. In the Properties window of the frmcnfg form, set the Text property to Screen Saver Setup.
  5. Add a Label control, add a TextBox control, and add two Button controls to the frmcnfg form.
  6. Set the following properties:
    • Label1
      Text: Enter Message
    • TextBox1
      Name: txtmessage
      Text: Enter Text Here
      Multiline: True
    • Button1
      Name: cmdOK
      Text: &OK
    • Button2
      Name: cmdCancel
      Text: &Cancel
  7. To accept the marquee text from the user and then to store the text in a registry, add the following code to the OK button of the frmcnfg form:
            'Save the current settings to
            'HKEY_CURRENT_USER\Software\
            'in the registry.
    
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Software", True)
            Dim newkey As RegistryKey = key.CreateSubKey("Test Screen Saver")
            newkey.SetValue("Message", txtmessage.Text)
            newkey.Close()
            Me.Close()
    

Complete Code Listing

Complete Code Listing (frmscr)

Imports Microsoft.Win32
Imports Microsoft.VisualBasic
Imports System.Math
Public Class frmscr
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'The Windows Form Designer requires this call.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call.

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer.
    Private components As System.ComponentModel.IContainer

    'NOTE: The Windows Form Designer requires the following procedure.
    'It can be modified by using the Windows Form Designer.  
    'Do not modify the procedure by using the Code editor.
    Friend WithEvents lblMessage As System.Windows.Forms.Label
    Friend WithEvents Timer1 As System.Windows.Forms.Timer
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.lblMessage = New System.Windows.Forms.Label
        Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
        Me.SuspendLayout()
        '
        'lblMessage
        '
        Me.lblMessage.AutoSize = True
        Me.lblMessage.BackColor = System.Drawing.Color.Black
        Me.lblMessage.ForeColor = System.Drawing.Color.Yellow
        Me.lblMessage.Location = New System.Drawing.Point(72, 118)
        Me.lblMessage.Name = "lblMessage"
        Me.lblMessage.Size = New System.Drawing.Size(193, 36)
        Me.lblMessage.TabIndex = 1
        Me.lblMessage.Text = "screen saver"
        Me.lblMessage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Timer1
        '
        Me.Timer1.Enabled = True
        '
        'frmscr
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(15, 33)
        Me.BackColor = System.Drawing.Color.Black
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.ControlBox = False
        Me.Controls.Add(Me.lblMessage)
        Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 21.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "frmscr"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.TopMost = True
        Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
        Me.ResumeLayout(False)

    End Sub

#End Region

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

        Dim tmpLng As Integer
        tmpLng = SystemParametersInfo(SPI_SCREENSAVERRUNNING, 1&, 0&, 0&)

        'Get the user's previous preference for the marquee message.

        Dim pRegKey As RegistryKey = Registry.CurrentUser
        pRegKey = pRegKey.OpenSubKey("Software\\Test Screen Saver")
        Dim val As Object = pRegKey.GetValue("Message")
        pRegKey.Close()
        lblMessage.Text = val.ToString

        'Make the cursor disappear.

        Me.Cursor.Current.Hide()
    End Sub

    Private Sub frmscr_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        'Immediately end when any key is pressed.
        Me.Close()
    End Sub

    Private Sub frmscr_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Activated
        'Center the lblMessage label to the form.
        lblMessage.Left = GetScaleWidth(Me)
        lblMessage.Top = (GetScaleWidth(Me) - lblMessage.Height) / 3
    End Sub

    Private Sub frmscr_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        'System.Windows.Forms.Cursor.Current.Show
        ''Restore the mouse cursor.
        Dim tmplng As Integer
        Me.Cursor.Current.Show()

        tmplng = SystemParametersInfo(SPI_SCREENSAVERRUNNING, 0&, 0&, 0&)
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Determine whether the Message has moved completely off the left side of the screen.
        If lblMessage.Left < (0 - lblMessage.Width) Then
            lblMessage.Left = GetScaleWidth(Me) 'ScaleWidth
        End If

        'Moves lblMessage to the left.
        lblMessage.Left = lblMessage.Left - 10


    End Sub

    Private Sub frmscr_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

        Static OldX As Integer
        Static OldY As Integer

        'Determines whether the mouse was moved and whether the movement was large.
        'if so, the screen saver is ended.
        If (OldX > 0 And OldY > 0) And (Abs(e.X - OldX) > 3 Or Abs(e.Y - OldY) > 3) Then
            Me.Close()

        End If

        'Assigns the current X and Y locations to OldX and OldY.
        OldX = e.X
        OldY = e.Y

    End Sub
End Class
Note You must change the code in Visual Basic 2005. By default, Visual Basic creates two files for the project when you create a Windows Forms project. If the form is named Form1, the two files that represent the form are named Form1.vb and Form1.Designer.vb. You write the code in the Form1.vb file. The Windows Forms Designer writes the code in the Form1.Designer.vb file. The Windows Forms Designer uses the partial keyword to divide the implementation of Form1 into two separate files. This behavior prevents the designer-generated code from being interspersed with your code.

For more information about the new Visual Basic 2005 language enhancements, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx
For more information about partial classes and the Windows Forms Designer, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/ms171843.aspx

Complete Code Listing (Module1)

Imports System.Runtime.InteropServices
Imports System.Environment

Module Module1

    Public Declare Auto Function SystemParametersInfo Lib "user32" (ByVal uAction As Integer, ByVal uParam As Integer, ByRef pvParam As Integer, ByVal fuWinIni As Integer) As Boolean
    Public Const SPI_SCREENSAVERRUNNING = 97&
    Public Const frmedge As Integer = 4
    Public nMouseMoves&
    Dim sStartType


    Public Sub Main(ByVal args As String())
        Dim Inst As Boolean = False


        If args.Length > 0 Then
            sStartType = args(0).ToLower.Trim().Substring(0, 2)

            If sStartType = "" Then
                'This will occur when a user right-clicks the .SCR
                'file and chooses "configure"
                sStartType = "/c"
            End If

            ' Determine whether the screen saver should show user-definable options.
            If sStartType = "/c" Then
                Dim usercnfg As New frmcnfg
                usercnfg.ShowDialog()

                ' Exit the application.
                Exit Sub
            End If

            ' Determine whether the screen saver should just execute.
            If sStartType = "/s" Then
                'Check for previous instance.
                Inst = PrevInstance()
                If Not (Inst) Then
                    ' Create a Screen Saver form and display the form.
                    Dim scrsvr As New frmscr
                    scrsvr.ShowDialog()
                Else
                    'If a previous instance exists, exit the application.
                    Exit Sub
                End If
            End If
        End If
    End Sub
 

    Function PrevInstance() As Boolean
        If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Function GetScaleWidth(ByVal frm As Form) As Integer

        Dim ctl As Control
        Dim w As Integer = frm.ClientSize.Width

        For Each ctl In frm.Controls
            With ctl
                If .GetContainerControl() Is frm Then
                    If .Dock = DockStyle.Left Or .Dock = DockStyle.Right Then
                        w = w - .Size.Width
                    End If
                End If
            End With
        Next
        GetScaleWidth = w - frmedge
    End Function

    

End Module

Complete Code Listing (frmcnfg)

Imports Microsoft.Win32
Public Class frmcnfg
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'The Windows Form Designer requires this call.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call.

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer.
    Private components As System.ComponentModel.IContainer

    'NOTE: The Windows Form Designer requires the following procedure.
    'It can be modified by using the Windows Form Designer.  
    'Do not modify the procedure by using the Code editor.
    Friend WithEvents txtmessage As System.Windows.Forms.TextBox
    Friend WithEvents cmdcancel As System.Windows.Forms.Button
    Friend WithEvents cmdOk As System.Windows.Forms.Button
    Friend WithEvents label1 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.cmdOk = New System.Windows.Forms.Button
        Me.cmdcancel = New System.Windows.Forms.Button
        Me.label1 = New System.Windows.Forms.Label
        Me.txtmessage = New System.Windows.Forms.TextBox
        Me.SuspendLayout()
        '
        'cmdOk
        '
        Me.cmdOk.Location = New System.Drawing.Point(200, 184)
        Me.cmdOk.Name = "cmdOk"
        Me.cmdOk.Size = New System.Drawing.Size(56, 24)
        Me.cmdOk.TabIndex = 0
        Me.cmdOk.Text = "&OK"
        '
        'cmdcancel
        '
        Me.cmdcancel.Location = New System.Drawing.Point(272, 184)
        Me.cmdcancel.Name = "cmdcancel"
        Me.cmdcancel.Size = New System.Drawing.Size(56, 24)
        Me.cmdcancel.TabIndex = 1
        Me.cmdcancel.Text = "&Cancel"
        '
        'label1
        '
        Me.label1.Location = New System.Drawing.Point(24, 40)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(152, 24)
        Me.label1.TabIndex = 2
        Me.label1.Text = "Enter Message"
        '
        'txtmessage
        '
        Me.txtmessage.Location = New System.Drawing.Point(32, 64)
        Me.txtmessage.Multiline = True
        Me.txtmessage.Name = "txtmessage"
        Me.txtmessage.Size = New System.Drawing.Size(296, 96)
        Me.txtmessage.TabIndex = 3
        Me.txtmessage.Text = ""
        '
        'frmcnfg
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(344, 221)
        Me.Controls.Add(Me.txtmessage)
        Me.Controls.Add(Me.label1)
        Me.Controls.Add(Me.cmdcancel)
        Me.Controls.Add(Me.cmdOk)
        Me.Name = "frmcnfg"
        Me.Text = "CONFIGURATION"
        Me.ResumeLayout(False)

    End Sub

#End Region


    Private Sub cmdcancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdcancel.Click
        Me.Close()
    End Sub

    Private Sub cmdOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
        'Save the current settings to
        'HKEY_CURRENT_USER\Software\
        'in the registry.


        Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Dim newkey As RegistryKey = key.CreateSubKey("Test Screen Saver")
        newkey.SetValue("Message", txtmessage.Text)
        newkey.Close()
        Me.Close()
    End Sub
End Class

Build and Test the Screen Saver

  1. On the Project menu, click MyScreenSaver Properties.
  2. In the MyScreenSaver Property Pages dialog box, click to select Sub Main in the Startup object combo box.
  3. On the Build menu, click Build Solution.
  4. To test the screen saver setup, follow these steps:
    1. On the Project menu, click MyScreenSaver Properties.
    2. In the MyScreenSaver Property Pages dialog box, click to select Configuration Properties, and then type /c in the Command line arguments text box on the right pane. Click OK.
    3. Press the F5 key to build and to run the program.

      The Screen Saver Setup dialog box is displayed.
    4. Type Test Screen Saver in the message box, and then click OK.
  5. To test the screen saver application, follow these steps:
    1. On the Project menu, click MyScreenSaver Properties.
    2. In the MyScreenSaver Property Pages dialog box, click to select Configuration Properties, and then type /s in the Command line arguments text box on the right pane. Click OK.
    3. Press the F5 key to build and to run the program.

      Test Screen Saver may be displayed in the Screen Saver list.

Register the Screen Saver

  1. Find the MyScreenSaver.exe file in the bin folder of the MyScreenSaver Application folder, and then rename the .exe file name extension .scr. For example, rename MyScreenSaver.exe as MyScreenSaver.scr.
  2. Copy the MyScreenSaver.scr file to the Windows directory.

    The MyScreenSaver option is available in the Screen Savers list.

REFERENCES

For information about how to create screen savers by using Microsoft DirectX, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/library/ms810488.aspx

Properties

Article ID: 818359 - Last Review: March 9, 2007 - Revision: 4.2
APPLIES TO
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbvs2005swept kbvs2005applies kbhowtomaster kbscreensaver kbdevstudio KB818359

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com