Visual Basic Q&A

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘exe project’

How to automate Outlook by using Visual Basic

Symptoms
This article demonstrates how to programmatically control Microsoft Outlook using Automation from Visual Basic. The example demonstrates creating contacts, creating appointments, and sending messages by using Microsoft Outlook’s object-model.
Resolution
Follow the steps below to create and run the example. To run the sample, you need an early-bound reference to a Microsoft Outlook type library. The following table lists the file names of the type libraries for the different versions of Microsoft Outlook:
Collapse this tableExpand this table
Outlook versionHow type library appears in references listFilenameOutlook 97″Microsoft Outlook 8.0 Object Library”msoutl8.olbmsoutl8.olb”Microsoft Outlook 98 Object Library”msoutl85.olbOutlook 2000″Microsoft Outlook 9.0 Object Library”msoutl9.olbOutlook 2002″Microsoft Outlook 10.0 Object Library”msoutl.olbOffice Outlook 2003″Microsoft Outlook 11.0 Object Library”msoutl.olb
Building the automation sampleStart Visual Basic, and create a new Standard EXE project.From the Project menu, choose References and select Microsoft Outlook.Add a button to your form.Double-click the button, and then add the following code:

‘ Start Outlook. ‘ If it is already running, you’ll use the same instance…Dim olApp As Outlook.ApplicationSet olApp = CreateObject(“Outlook.Application”)’ Logon. Doesn’t hurt if you are already running and logged on…Dim olNs As Outlook.NameSpaceSet olNs = olApp.GetNamespace(“MAPI”)olNs.Logon ‘ Create and Open a new contact.Dim olItem As Outlook.ContactItemSet olItem = olApp.CreateItem(olContactItem) ‘ Setup Contact information…With olItem.FullName = “James Smith”.Birthday = “9/15/1975″.CompanyName = “Microsoft”.HomeTelephoneNumber = “704-555-8888″.Email1Address = “someone@microsoft.com”.JobTitle = “Developer”.HomeAddress = “111 Main St.” & vbCr & “Charlotte, NC 28226″End With’ Save Contact…olItem.Save’ Create a new appointment.Dim olAppt As Outlook.AppointmentItemSet olAppt = olApp.CreateItem(olAppointmentItem)’ Set start time for 2-minutes from now…olAppt.Start = Now() + (2# / 24# / 60#)’ Setup other appointment information…With olAppt.Duration = 60.Subject = “Meeting to discuss plans…”.Body = “Meeting with ” & olItem.FullName & ” to discuss plans.”.Location = “Home Office”.ReminderMinutesBeforeStart = 1.ReminderSet = TrueEnd With’ Save Appointment…olAppt.Save’ Send a message to your new contact.Dim olMail As Outlook.MailItemSet olMail = olApp.CreateItem(olMailItem) ‘ Fill out & send message…olMail.To = olItem.Email1AddressolMail.Subject = “About our meeting…”olMail.Body = _”Dear ” & olItem.FirstName & “, ” & vbCr & vbCr & vbTab & _”I’ll see you in 2 minutes for our meeting!” & vbCr & vbCr & _”Btw: I’ve added you to my contact list.”olMail.Send’ Clean up…MsgBox “All done…”, vbMsgBoxSetForegroundolNS.LogoffSet olNs = NothingSet olMail = NothingSet olAppt = NothingSet olItem = NothingSet olApp = Nothing Run the project, and click the button to run the code. Once the code runs, you should have a new contact named “James Smith,” an appointment scheduled in two minutes with a reminder to appear in one minute, and have sent a message to someone@microsoft.com. Also, because you added a birthday for your contact (9/15), a recurring event was added for your Outlook Calendar to remind you of the day.
New to Outlook 2002 are the two dialog boxes: one warning you that a program is trying to access e-mail addresses you have stored in Outlook and asking if you want to allow this, and another message to the effect that a program is trying to send e-mail. This feature will protect you from unknowingly being used by a virus that sends e-mail from your system.
For more information, click the following article number to view the article in the Microsoft Knowledge Base:
290500?(http://support.microsoft.com/kb/290500/) Description of the developer-related e-mail security features in Outlook 2002

How To Display Hierarchical Data Using the MSHFlexGrid

Symptoms
As its name suggests, the MSHFlexGrid control that ships with Visual Basic6.0 allows database data to be displayed in an aggregated, hierarchicalformat. Using this control in conjunction with the Data EnvironmentDesigner, developers can easily and logically display information containedin several different database tables, which are connected through the useof foreign keys.
Resolution
The Data Environment Designer is a tool that enables developers toencapsulate ActiveX Data Object (ADO) connection and command objects in areusable Visual Basic object. This sample project makes use of a DataEnvironment Designer to establish a connection to SQL Server and toretrieve related data from two tables in the Pubs sample database viacommand objects. The related data is then displayed in a hierarchicalformat in the MSHFlexGrid control.
To create this sample, do the following:Create a new Standard EXE project. Form1 is created by default.On the Project menu, click Components, and click the Designers tab inthe Components window. On the Designers tab, make sure that the DataEnvironment check box is selected. On the Controls tab, select the checkbox next to the Microsoft Hierarchical FlexGrid Control 6.0 option. Thenclick OK to exit the Components window.On the Project menu, click Add Data Environment, which adds theDataEnvironment1 object to your project.If the object window for the DataEnvironment1 object is not visible,right-click the DataEnvironment1 object in Project Explorer and selectView Object.In the DataEnvironment1 object window, right-click the Connection1 iconpictured beneath the DataEnvironment1 icon and select the Propertiesoption from the pop-up menu (this displays the Data Link Propertieswindow).Select the Use Connection String option, and click Build. Select theMicrosoft OLE DB Provider for SQL Server option, and click Next.Under step 1 on the Connection tab, select or enter the name of the SQLServer that you are using for this project.Under step 2, enter a user name and password that are valid values foryour SQL Server Environment. Also select the Allow Saving Of Passwordcheck box.Under step 3, select the Pubs sample database from the combo box. ClickTest to test your connection information. If your test is successful,click OK to exit the Data Link Properties window.Right-click the Connection1 icon in the object window for theDataEnvironment1 object. Select the Add Command option from the pop-upmenu to add a new command object to your project.Right-click the new Command1 icon in the DataEnvironment1 objectwindow and select the Properties option from the pop-up window (thisdisplays the Command1 Properties window).On the General tab, select the SQL Statement option button and cut andpaste the following code into the enabled text box:

SELECT pub_id, pub_name FROM Publishers Then click OK to close the Command1 Properties window.Right-click the Command1 icon in the DataEnvironment1 object window,and select the Add Child Command option from the pop-up menu (this addsanother icon to the DataEnvironment1 object window called Command2).Right-click the Command2 icon in the DataEnvironment1 object window andselect the Properties option from the pop-up menu (this displays theCommand2 Properties window).On the General tab, select the SQL Statement option button and cut andpaste the following code into the enabled text box:

SELECT pub_id, title, price FROM Titles On the Relation tab, make sure that the pub_id value is selected inboth the Parent Fields and the Child Fields/Parameters combo boxes. Thenclick Add (this creates a hierarchical relationship between the pub_idfields that are selected in the two command objects).Place an MSHFlexGrid control onto Form1, the default form of theproject.Select the MSHFlexGrid control that you added to Form1, then select theProperties window.Select the DataEnvironment1 option for the DataSource property, andselect the Command1 option for the DataMember property.Now run your project. The MSHFlexGrid control is filled with data fromboth the Publishers and Titles tables of the Pubs database, and theinformation is hierarchically grouped.NOTE: The results of steps 18 and 19 can also be accomplished at run timeby adding the following code to the code window of Form1:

Option ExplicitPrivate Sub Form_Load()DataEnvironment1.Command1Set MSHFlexGrid1.DataSource = DataEnvironment1.rsCommand1End Sub

How To Compile VB Programs with Debug Symbols Embedded

Symptoms
The “Compile to Native Code” option introduced in Visual Basic versions 5.0 and 6.0 not only improves performance of Visual Basic programs and components, but also makes it possible to debug them with the Visual C++ debugger.
This article shows you how to compile a Visual Basic program or componentwith embedded debug symbols. By doing so, you simplify the debuggingprocess and avoid the problems associated with mismatched and improperlyplaced symbols.
Resolution
All it takes to compile a Visual Basic program or component with embeddeddebug symbols is a properly set environment variable, LINK. The key is toset it in such a way that Visual Basic inherits the setting when it islaunched. To do this, follow the steps below:
There are several ways to set the LINK environment variable, each of thesemethods is outlined below:
Windows NT or Windows 95/98/MeOpen an MS-DOS Prompt.Navigate to the folder containing Visual Basic.Execute the following command, “set link=/pdb:none” without quotes.Start Visual Basic from the MS-DOS command prompt.
Windows NT OnlyFrom the Control Panel, select the System icon.Select the Environment tab.In the Variable entry, enter “link” without quotes.In the Value entry, enter the following:
/pdb:nonePress Set, then Apply.Start Visual Basic from the MS-DOS command prompt.
Windows 95/98/Me OnlyMake a backup copy of the AutoExec.Bat file.Open the Autoexec.bat file with Notepad.Exe or any text editor.Add the following entry to the AutoExec.Bat file:
set link=/pdb:noneSave the AutoExec.Bat file.Execute the AutoExec.Bat file or reboot the machine.Start Visual Basic.
Once the LINK environment variable is set, a Visual Basic project can becompiled with embedded debug symbols. The following steps describe howto create a test program and compile it with embedded debug symbols:
Step-by-Step ExampleCreate a new Standard EXE project in Visual Basic. Form1 is created bydefault.Add a CommandButton (Command1) to Form1.Add the following code to Form1:

Private Sub Command1_Click()Dim s As Strings = App.EXENamePrint sEnd Sub Select Project1 Properties from the Project menu.Select the Compile tab.Select Compile to Native Code, check Create Symbolic Debug Info, andselect No Optimization.Save the project and create Project1.EXE. Note that the EXE is createdwith embedded debug symbols.

How To Associate a Custom Icon with a Formless Visual Basic Application

Symptoms
For Visual Basic applications that do not contain forms, you can still provide a custom icon for the executable. This article explains how you can add an icon resource to the project.
Resolution
When you create a Visual Basic executable application, you can select an icon from one of the project’s forms in the Icon drop-down list box on the Make tab of the Project Properties dialog box to use as the icon for the executable file. However, if there are no forms in the project, no icons are available in the drop-down list box of the Make tab. In this case, you can create a custom icon resource in your project. The compiler uses this resource as the icon for your executable file. If you include more than one icon, the compiler uses the icon whose letter appears first in the alphabet because it prioritizes alphabetically.
The following sample demonstrates how to provide a custom icon for a simple, formless Visual Basic EXE project. For this sample, you may select an icon from your system, or you can create your own. By default, Visual Basic 6.0 installs icons in the following folder:
C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\ To create your own icon, you can use a tool such as Image Editor, which is available from the Visual Basic 6.0 CD (Disk 1) or the Visual Studio 6.0 CD (Disk 3) at the following location:
\Common\Tools\VB\Imagedit\Imagedit.exe
Step-by-Step ExampleCreate a new Visual Basic standard EXE project. Form1 is created by default.Right-click Form1 in the Project window, and then click Remove Form1 to remove the form from the project.Add a new standard module (Module1) to the project.Paste the following code into the code window of Module1:

Public Sub Main()MsgBox “Hello World”End Sub Select an icon from the list, or use Image Editor (or another appropriate tool) to create an icon file.To load the Visual Basic Resource Editor, follow these steps:From the Add-Ins menu, click Add-In Manager.Locate VB 6 Resource Editor in the list of available add-ins.Double-click VB 6 Resource Editor to load the editor add-in.From the Tools menu, click Resource Editor.In the Resource Editor window, click Add Icon on the toolbar. (This button appears as a small gray square that is outlined in blue.)Open the icon file that you created earlier.By default, the icon is added with the name “101″. Right-click the icon resource that was just added, and then click Properties.In the Id box, type APPICON to rename the icon resource, and then click OK.
NOTE: “APPICON” is just a suggested name for your resource. If you already have other, named icon resources, make sure that your executable icon begins with a letter that occurs later in the alphabet than the other icons. For example, if you have an icon that is named “AAA” and another that is named “BBB”, the compiler uses the one that is named “AAA” as your application icon.From the File menu, click Make to compile the Visual Basic project.In Windows Explorer, browse to the location where you compiled your executable file. Notice that the icon for the executable file is the icon that you selected in the Resource Editor.

How To Load and Unload a User Profile into the Registry with Visual Basic

Symptoms
This article describes how to use the RegLoadKey registry function to load a user profile into the registry and, subsequently, how to use RegUnLoadKey to unload the user profile. Because RegLoadKey requires the SE_RESTORE_NAME privilege to be successful, this article also uses the OpenProcessToken, LookupPrivilegeValue, and AdjustTokenPrivileges functions.
Resolution
In part, the registry consists of files that store information about a user profile. When this file is loaded, it maps to the HKEY_USERS or HKEY_LOCAL_MACHINE key, whichever is specified in the call to RegLoadKey.
To retrieve user profile-specific information, you can load the NtUser.dat file that is located in the profile path of the user profile that you want to load. It may be necessary to load a hive (user profile) when you try to provide profile-specific data. For example, either the ImpersonateLoggedOnUser function or the CreateProcessAsUser function is generally used to run under a different security context and does not load the profile of that user.
The following steps illustrate how to load NtUser.dat and unload it when finished. These methods are not a threat to security because they only succeed if the calling process and the impersonated user have sufficient privileges.
Step-by-Step ExampleWARNING: If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.
Create a new Standard EXE project in Visual Basic. Form1 is created by default.Add a TextBox control (Text1) and two CommandButton controls (Command1 and Command2) to Form1.Paste the following code into the General Declarations section of Form1:

Option ExplicitPrivate Type LUIDLowPart As LongHighPart As LongEnd TypePrivate Type LUID_AND_ATTRIBUTESpLuid As LUIDAttributes As LongEnd TypePrivate Type TOKEN_PRIVILEGESPrivilegeCount As LongPrivileges(1) As LUID_AND_ATTRIBUTESEnd TypePrivate Const TOKEN_ADJUST_PRIVLEGES = &H20Private Const TOKEN_QUERY = &H8Private Const SE_PRIVILEGE_ENABLED = &H2Private Const HKEY_USERS = &H80000003Private Const SE_RESTORE_NAME = “SeRestorePrivilege”Private Const SE_BACKUP_NAME = “SeBackupPrivilege”Private Declare Function GetCurrentProcess Lib “kernel32″ () As LongPrivate Declare Function OpenProcessToken Lib “advapi32.dll” _(ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _TokenHandle As Long) As LongPrivate Declare Function LookupPrivilegeValue Lib “advapi32.dll” Alias _”LookupPrivilegeValueA” (ByVal lpSystemName As String, _ByVal lpName As String, lpLuid As LUID) As LongPrivate Declare Function AdjustTokenPrivileges Lib “advapi32.dll” _(ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, _NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, _ByVal PreviousState As Long, ByVal ReturnLength As Long) As LongPrivate Declare Function RegLoadKey Lib “advapi32.dll” Alias “RegLoadKeyA” _(ByVal hKey As Long, ByVal lpSubKey As String, ByVal lpFile As String) _As LongPrivate Declare Function RegUnLoadKey Lib “advapi32.dll” Alias “RegUnLoadKeyA” _(ByVal hKey As Long, ByVal lpSubKey As String) As LongPrivate Retval As LongPrivate strKeyName As StringPrivate MyToken As LongPrivate TP As TOKEN_PRIVILEGESPrivate RestoreLuid As LUIDPrivate BackupLuid As LUIDPrivate Sub Form_Load()strKeyName = “keyLoaded”‘ Path to file on Windows NT: C:\WinNT\Profiles\<Profile Name>\NtUser.Dat’ Path to file on Windows 2000: C:\Documents and Settings\<Profile Name>\NtUser.DatText1.Text = “<Path to File>”Command2.Enabled = FalseRetval = OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVLEGES _Or TOKEN_QUERY, MyToken)If Retval = 0 Then MsgBox “OpenProcess: ” & Err.LastDllErrorRetval = LookupPrivilegeValue(vbNullString, SE_RESTORE_NAME, _RestoreLuid)If Retval = 0 Then MsgBox “LookupPrivileges: ” & Err.LastDllErrorRetval = LookupPrivilegeValue(vbNullString, SE_BACKUP_NAME, BackupLuid)If Retval = 0 Then MsgBox “LookupPrivileges: ” & RetvalTP.PrivilegeCount = 2TP.Privileges(0).pLuid = RestoreLuidTP.Privileges(0).Attributes = SE_PRIVILEGE_ENABLEDTP.Privileges(1).pLuid = BackupLuidTP.Privileges(1).Attributes = SE_PRIVILEGE_ENABLEDRetval = AdjustTokenPrivileges(MyToken, vbFalse, TP, Len(TP), 0&, 0&)If Retval = 0 Then MsgBox “AdjustTokenPrivileges: ” & Err.LastDllErrorEnd SubPrivate Sub Command1_Click()Retval = RegLoadKey(HKEY_USERS, strKeyName, Text1.Text)If Retval <> 0 Then MsgBox “RegLoadKey: ” & RetvalCommand2.Enabled = TrueEnd SubPrivate Sub Command2_Click()Retval = RegUnLoadKey(HKEY_USERS, strKeyName)If Retval <> 0 Then MsgBox “RegUnloadKey: ” & RetvalEnd SubPrivate Sub Form_Unload(Cancel As Integer)Retval = AdjustTokenPrivileges(MyToken, vbTrue, TP, Len(TP), 0&, 0&)If Retval = 0 Then MsgBox “AdjustTokenPrivileges: ” & Err.LastDllErrorEnd Sub Save the project, and then press the F5 key to run it.Type the path to a specific user profile .dat file, for example:
C:\WinNT\Profiles\Administrator\NtUser.dat and then click Command1.Click Start, click Run, type regedit (on Windows NT) or regedt32 (on Windows 2000), and then click OK.Locate the HKEY_USERS subtree. Notice that this subtree includes the new key, KeyLoaded.In the Visual Basic project, click Command2 to remove this key from the registry.