Microsoft KB Archive/818359

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

Article ID: 818359

Article Last Modified on 3/9/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



IN THIS TASK

 * SUMMARY
 * Create the Screen Saver Project
 * Add the Screen Saver Setup Form
 * Complete Code Listing
 * Complete Code Listing (frmscr)
 * Complete Code Listing (Module1)
 * Complete Code Listing (frmcnfg)
 * Build and Test the Screen Saver
 * Register the Screen Saver
 * REFERENCES



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.

back to the top

Create the Screen Saver Project
 Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. 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. Name the project MyScreenSaver, and then click OK.

By default, Form1 is created. Set the properties of Form1 as follows:  Name: frmscr  ControlBox: False </li> MaximizeBox: False </li> MinimizeBox: False </li> BackColor: Black </li> Text: &quot;&quot;(no text) </li> TopMost: True </li> WindowState: Maximized </li></ul> </li> In the Solution Explorer window, right-click Form1, and then click Properties.</li> In the File Properties window, set the File Name property to frmscr.vb .</li> Add a Label control.

By default, Label1 is added to the form.</li> Set the properties of Label1 as follows: <ul> Name: lblMessage </li> ForeColor: Yellow </li></ul> </li> Add a Timer control.

Timer1 is added to the form.</li> Set the Enabled property of the timer to True .</li>  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(&quot;Software\Test Screen Saver&quot;, True) Dim val As Object = pRegKey.GetValue(&quot;Message&quot;, &quot;Enter Text here&quot;) 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. </li>  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 </li> <li> 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 </li> <li> 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&) </li> <li> 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 </li> <li>On the Project menu, click Add Module.

By default, Module1 is created.</li> <li> 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 = &quot;&quot; Then 'This will occur when a user right-clicks the .scr 'file and then selects &quot;configure&quot; sStartType = &quot;/c&quot; End If

' Determine whether the screen saver should show user definable options. If sStartType = &quot;/c&quot; 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 = &quot;/s&quot; 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. </li> <li> 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 back to the top </li></ol>

Add the Screen Saver Setup Form
<ol> <li>On the Project menu, click Add Windows Form.</li> <li>In the Add New Item dialog box, click Windows Form under Templates.</li> <li>Type frmcnfg in the Name text box, and then click Open.</li> <li>In the Properties window of the frmcnfg form, set the Text property to Screen Saver Setup .</li> <li>Add a Label control, add a TextBox control, and add two Button controls to the frmcnfg form.</li> <li>Set the following properties: <ul> <li>Label1

Text: Enter Message

</li> <li>TextBox1

Name: txtmessage

Text: Enter Text Here

Multiline: True

</li> <li>Button1

Name: cmdOK

Text: &OK

</li> <li>Button2

Name: cmdCancel

Text: &Cancel

</li></ul> </li> <li> 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(&quot;Software&quot;, True) Dim newkey As RegistryKey = key.CreateSubKey(&quot;Test Screen Saver&quot;) newkey.SetValue(&quot;Message&quot;, txtmessage.Text) newkey.Close Me.Close </li></ol>

back to the top

Complete Code Listing (frmscr)
Imports Microsoft.Win32 Imports Microsoft.VisualBasic Imports System.Math Public Class frmscr Inherits System.Windows.Forms.Form


 * 1) Region &quot; Windows Form Designer generated code &quot;

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 = &quot;lblMessage&quot; Me.lblMessage.Size = New System.Drawing.Size(193, 36) Me.lblMessage.TabIndex = 1 Me.lblMessage.Text = &quot;screen saver&quot; 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(&quot;Microsoft Sans Serif&quot;, 21.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = &quot;frmscr&quot; Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.TopMost = True Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me.ResumeLayout(False)

End Sub


 * 1) 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(&quot;Software\\Test Screen Saver&quot;) Dim val As Object = pRegKey.GetValue(&quot;Message&quot;) 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

back to the top

Complete Code Listing (Module1)
Imports System.Runtime.InteropServices Imports System.Environment

Module Module1

Public Declare Auto Function SystemParametersInfo Lib &quot;user32&quot; (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 = &quot;&quot; Then 'This will occur when a user right-clicks the .SCR 'file and chooses &quot;configure&quot; sStartType = &quot;/c&quot; End If

' Determine whether the screen saver should show user-definable options. If sStartType = &quot;/c&quot; 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 = &quot;/s&quot; 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 back to the top

Complete Code Listing (frmcnfg)
Imports Microsoft.Win32 Public Class frmcnfg Inherits System.Windows.Forms.Form


 * 1) Region &quot; Windows Form Designer generated code &quot;

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 = &quot;cmdOk&quot; Me.cmdOk.Size = New System.Drawing.Size(56, 24) Me.cmdOk.TabIndex = 0 Me.cmdOk.Text = &quot;&OK&quot; '       'cmdcancel '       Me.cmdcancel.Location = New System.Drawing.Point(272, 184) Me.cmdcancel.Name = &quot;cmdcancel&quot; Me.cmdcancel.Size = New System.Drawing.Size(56, 24) Me.cmdcancel.TabIndex = 1 Me.cmdcancel.Text = &quot;&Cancel&quot; '       'label1 '       Me.label1.Location = New System.Drawing.Point(24, 40) Me.label1.Name = &quot;label1&quot; Me.label1.Size = New System.Drawing.Size(152, 24) Me.label1.TabIndex = 2 Me.label1.Text = &quot;Enter Message&quot; '       'txtmessage '       Me.txtmessage.Location = New System.Drawing.Point(32, 64) Me.txtmessage.Multiline = True Me.txtmessage.Name = &quot;txtmessage&quot; Me.txtmessage.Size = New System.Drawing.Size(296, 96) Me.txtmessage.TabIndex = 3 Me.txtmessage.Text = &quot;&quot; '       '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 = &quot;frmcnfg&quot; Me.Text = &quot;CONFIGURATION&quot; Me.ResumeLayout(False)

End Sub


 * 1) 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(&quot;Software&quot;, True) Dim newkey As RegistryKey = key.CreateSubKey(&quot;Test Screen Saver&quot;) newkey.SetValue(&quot;Message&quot;, txtmessage.Text) newkey.Close Me.Close End Sub End Class back to the top

Build and Test the Screen Saver
<ol> <li>On the Project menu, click MyScreenSaver Properties.</li> <li>In the MyScreenSaver Property Pages dialog box, click to select Sub Main in the Startup object combo box.</li> <li>On the Build menu, click Build Solution.</li> <li>To test the screen saver setup, follow these steps: <ol style="list-style-type: lower-alpha;"> <li>On the Project menu, click MyScreenSaver Properties.</li> <li>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.</li> <li>Press the F5 key to build and to run the program.

The Screen Saver Setup dialog box is displayed.</li> <li>Type Test Screen Saver in the message box, and then click OK.</li></ol> </li> <li>To test the screen saver application, follow these steps: <ol style="list-style-type: lower-alpha;"> <li>On the Project menu, click MyScreenSaver Properties.</li> <li>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.</li> <li>Press the F5 key to build and to run the program.

Test Screen Saver may be displayed in the Screen Saver list.</li></ol> </li></ol>

back to the top

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.

back to the top

<div class="references_section">