K & K Consulting    K & K Consulting

K&K Home VB Guru Home Search VB Site VB Code VB Tips VB Tutorials VB Questions

K&K Home
Up
Multiple Inst Code
SQL-Assignment Code
Recycle Bin Code
VB App Wait
VB Short Cuts


VB Tips & Tricks

 

If I find a short cut or tip, I will post it here.  If you have a short cut or tip, please feel free post below Add A VB Tip.

Name & Date Posted

Tip

The Guru
May 03, 2001

Microsoft Wheel Mouse In The VB IDE

I have had a few visitors ask me why the wheel on any Microsoft mouse will not work in the VB IDE.  Well basically, the answer is, you have not installed the proper drives for your mouse.  You are probably just using the default driver that came with your system or with Windows. So download the driver, Install it, pick the mouse you have, and scroll away in the VB IDE.

Click Here To Get Your Driver

 


The Guru
March 20, 2001
Posted from searchVB.com

Encryption made simple

If you've ever written an application that stores passwords, you'll know the
importance of encryption. There's no point in password protecting things if all
a user has to do is open a file or database to get all of the stored passwords.
It is possible, however, to write a very simple function that will both encrypt
and decrypt passwords. Simply pass the function the string you wish to encrypt,
and a short key (to make it harder to break your encryption), and it will return
the encrypted version. Pass it the encrypted version, and it will translate it
back into plain text. Enjoy.

Private Function Encrypt(ByVal strInput As String, ByVal strKey As String) As
String
Dim iCount As Long
Dim lngPtr As Long
    For iCount = 1 To Len(strInput)
        Mid(strInput, iCount, 1) = Chr((Asc(Mid(strInput, iCount, 1))) Xor
(Asc(Mid(strKey, lngPtr + 1, 1))))
        lngPtr = ((lngPtr + 1) Mod Len(strKey))
    Next iCount
    Encrypt = strInput
End Function

The Guru
Nov 19, 2000
Posted Microsoft

Visual Basic IDE Short Cuts

Here Is a complete listing of key shortcuts for the Visual Basic IDE.  The list is long, so Click here to view it.

The Guru
Nov 11, 2000
Posted Microsoft

COM+ Tips

COM+ and Windows 2000: Ten Tips and Tricks for Maximizing COM+ Performance.

 

Latest Review Just In

The Guru
Oct 27, 2000
Posted from VB2theMax

Silent install

VB6 Deployment and Packaging Wizard's resulting setup.exe has a command line switch that allows for a silent install. This feature is virtually undocumented except in the source code for Setup1.exe. The default path for the project file of Setup1 is:

C:\Program Files\Microsoft Visual Studio\VB98\Wizards\PDWizard\Setup1\Setup1.vbp

To do a silent install, the following syntax is required:

setup.exe /s c:\anylogfilename.log

The filename that follows the /s parameter must include the full path name.

The silent install is only interupted (that I could see) when the install encounters the "Setup is attempting to copy a file that is older than the one currently..." dialog. This interruption doesn't occur if the setup contains the latest versions of the files being installed.

 

The Guru
Oct 27, 2000
Posted from VB2theMax

Access an ADO Recordset Faster

The ADO Recorset object exposes a hidden, undocumented member: the Collect property. This property is functionally similar to the Field's Value property, but it's faster because it doesn't need a reference (explicit or implicit) to the Field object. You can use this property by passing a numeric index or a field's name, as in:

Dim rs As New ADODB.Recordset rs.Open "authors", "DSN=pubs"
    
'reference by field's name
firstName = rs.Collect("au_fname")
' reference by field's index
rs.Collect(2) = "John Doe"

Under ADO 2.5, the Collect property appears to be about 30% faster than the standard way to refer to a field's value.

 

The Guru
Oct 17, 2000
Posted from searchVB.com

Make Your VB App Wait

The tip involves making a VB app wait for the completion of some other process outside VB. This code is long, so Click Here to go view the code.

 

 

The Guru
Oct 07, 2000
Posted from searchVB.com

SQL-Assignment Troubles

Here is another solution to assigning strings in SQL statements this code is long, so Click Here to go view the code

 

Chintamani Bivalkar
Oct 07, 2000

Update To Prevent Multiple VB application instances

Chintamani writes:

Hi guru , I am a primary grade student of VB. I always visit your site for tips & code. In one of your tips..you had given a code for "Prevent Multiple VB application instances" (june23) I had gone thru some books & felt that similar thing can be achieved by following code 

Private Sub Form_Load() 
  If App.PrevInstance = True Then 
    Unload Me 
    Exit Sub 
  End If 
End Sub 

This code being very short & easy I think this should help very much 

The Guru's Notes:

Thanks for the update Chintamani, but I would just like to add the following "Gotcha" notes.

Since a computer running Windows NT can support multiple desktops, if you use a component designed to work with distributed COM, it can result in the following scenario:
bullet A client program in a user desktop requests one of the objects the component provides. Because the component is physically located on the same machine, the component is started in the user desktop.

bullet Subsequently, a client program on another computer uses distributed COM to request one of the objects the component provides. A second instance of the component is started, in a system desktop.

There are now two instances of the component running on the same NT computer, in different desktops.

This scenario is not a problem unless the author of the component has placed a test for App.PrevInstance in the startup code for the component to prevent multiple copies of the component from running on the same computer. In this case, the remote component creation will fail.

Also, although App.PrevInstance is supported in VB for CE, it does not work properly and can cause some major debugging head aches.  If your application does not fall into either of these two categories, then your code will work nicely.

 

The Guru
July12, 2000
Posted from Element K Journals

Avoid Variable Type Comparison Glitches In Textboxes

When you retrieve a numeric value from a textbox, you may want to compare it to some other preset value. For example, consider the following code:

Select Case Text1.Text
   Case 1 to 12
      MsgBox "Acceptable Value"
   Case Else
      MsgBox "Unacceptable Value"
End Select

You might think that this code would compare a numeric value in Text1 and return Acceptable Value for values 1 through 12, and Unacceptable Value for all other numbers. Instead, this code snippet displays the Acceptable Value message for only 1, 10, 11, and 12, but not 2, 3, 4, etc. That's because a textbox's Text property returns the value as a string, and so compares them as such in the Select Case statement.
To avoid this unexpected glitch, convert the numbers with the Val() function. This function automatically converts a string into the appropriate type: integer, long, single, or double. The modified code would look as follows:

Select Case Val(Text1.Text)
   Case 1 to 12
      MsgBox "Acceptable Value"
   Case Else
      MsgBox "Unacceptable Value"
End Select

 
The Guru
July 12, 2000

VARIABLE DECLARATION

Most high level programming languages force the developer to explicitly declare a variable before using it. Visual Basic is a notable exception. In fact, by default, VB's installation leaves the Visual Basic environment in a state where variable declaration is not required.
After installing Visual Basic, immediately select Tools-Options and check on REQUIRE VARIABLE DECLARATION. 

Selecting this option causes Visual Basic to insert the statement OPTION EXPLICIT into the General Declarations Section of each module in your project. The result is that an attempt to refer to a variable in code without first declaring it results in a compiler error.
What's the big deal, you might ask? Is there really a harm in leaving this option checked off? Suppose you use a variable in code that you haven't declared? Visual Basic is a programmer friendly language-won't VB take care of it? 
The answer is yes. VB will take care of it, but the price of a mistake on your part can be huge. 
For instance, suppose you assign a value to a variable called sngUnitPrice like this...

sngUnitPrice = 13.48 

And then later in your code you attempt to refer to this variable in a calculation, but accidentally refer to it by an incorrect name, for instance sngUnitCost (yes, it can happen!)

sngTotalPrice = sngUnitCost * m_intQuantity 

You're expecting the program to come up with a valid price. Instead,the result will be zero, since the value of the incorrectly named variable sngUnitCost is zero!When you tell VB to enforce variable declaration, errors like these are caught at compile time, potentially preventing disastrous results from occurring.

The Guru
June 29, 2000
Posted from Element K Journals

How to build a data-shaped SQL clause for VB

Since it's introduction in ADO 2.0, data shaping has remained largely on the fringes of Visual Basic arcanum. Relegated to the back pages of musty manuals, you may have overlooked this useful aspect of ADO. If you're not familiar with data-shaping, in essence, it lets you create recordsets within recordsets--or parent/child relationships--all with a  single ADO object. This means no messy joins, no complicated filtering, and no need for spaghetti-code in presentation logic. Data shaping reduces the amount of traffic crossing a network, provides more flexibility when using aggregate functions, and reduces overhead when interfacing with leading-edge tools like XML.

To create a shaped recordset, you use a standard SQL statement, along with three major keywords: SHAPE, APPEND, and RELATE, like so

SHAPE {SELECT EmployeeID,FirstName, LastName 
FROM Employees} 
APPEND ({SELECT OrderID, shipname, EmployeeID 
FROM orders} AS SomeAlias 
RELATE EmployeeID TO EmployeeID);

The SHAPE keyword specifies and defines the parent recordset. Once you create a parent object, you next APPEND the child recordset. This clause uses a similar syntax as SHAPE and contains the necessary SQL statement to create the child recordset within the parent. In addition to the child recordset's SQL statement, you must also indicate how you want the two recordsets to RELATE.

 

The Guru
June 25, 2000

See if a String is Blank

There are several ways to decide whether a string is blank:
    Dim txt As String
    Dim blank As String

        blank = ""
            : 
        If Len(txt) = 0 Then ...
        If txt = vbNullString Then ...
        If txt = "" Then ... 
        If txt = blank Then ...
The test Len(txt) = 0 is roughly 20 percent faster than the others.
The Guru
June 23, 2000
Posted from Element K Journals

Prevent Multiple VB application instances

This code is long, so Click Here to go view the code

 

The Guru
June 19, 2000
Posted from Microsoft Site

Don't lose focus in UserControls

Typically, to determine when a UserControl gains and loses focus, you might think to use the standard GotFocus and LostFocus events. However, in UserControls these two events aren't always reliable. There are situations where a control will lose the focus without firing the LostFocus event (for example, when Alt+Tabbing to another application), and also get the focus without firing the GotFocus event. As a result, your best bet for monitoring the focus status is to insert code in the UserControl's EnterFocus and ExitFocus events.

The Guru
June 15, 2000

Cint() Tip

The CInt() function rounds to the nearest integer value. In other words, CInt(2.4) returns 2, and CInt(2.6) returns 3. 

This function exhibits an under-documented behavior when the fractional part is equal to 0.5. In this case, this function rounds down if the integer portion of the argument is even, but it rounds up if the integer portion is an odd number. For example, CInt(2.5) returns 2, but CInt(3.5) returns 4.

The Guru
June 14, 2000
Posted from Element K Journals

Add pop-up menu support to the Rich Textbox control

While Visual Basic provides an easy way to create shortcut menus, some controls 
such as rich text boxes don't inherently support pop-up menus. To overcome this 
obstacle, you can take advantage of the MouseDown() event. Visual Basic triggers 
this event when you press the mouse button. To provide a pop-up menu, create a 
shortcut menu, then simply call it in the control's MouseDown() event.

To see how this works, add a Rich Textbox control to a sample form. Next, select 
Tools | Menu Editor from Visual Basic's IDE menu bar, and create a simple menu 
with one or two items. Then, switch to the form's code window, and enter 

Private Sub RichTextBox1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
   If Button = vbRightButton Then
      Me.PopupMenu Menu
   End IF
End Sub

The Guru
June 12, 2000
Posted from Microsoft Site

Uncover internal DLL functions with Dependency Walker

While the Windows API functions are fairly well documented, you may come across other DLL files that remain a mystery. For example, suppose you want to incorporate the MIDAS digital audio player into your application. The help files that come with this free DLL list all the important external function names. However, because the DLL doesn't support Visual Basic, you must hook into the DLL with API declarations. The internal names supported in this library aren't in the help files.

To unravel this mystery, you can use the Dependency Walker, a handy utility that comes with Visual Studio (appears as Depends on the Windows program menu). Simply point the utility to the DLL in question, and it will list all the internal file names that you'll need to refer to in your API declarations. For example, in the MIDAS DLL, you use a function called MIDASplayModule to play a sound module. However, the internal name for the function is _MIDASplayModule@8. As a result, you must declare the function in Visual Basic like so

Declare Function MIDASplayModule Lib "midas11.dll" Alias _
     "_MIDASplayModule@8" (ByVal module As Long, ByVal loopSong _
     As Boolean) As Long


Mike Coleman via Element K Journals
June 07, 2000

Move files to the Recycle Bin with VB and Windows API

This code is long, so Click Here to go view the code

 

The Guru
June 05, 2000
Posted from Microsoft Site

Win API Viewer

When you use the Windows API, you should never need to write your own Declare statement. The API Text Viewer utility loads in a text file (WIN31API.TXT for 16-bit, and WIN32API.TXT for 32-bit) and lets you copy declares, global constants, and user-defined types. You can also convert the text file to an Access database for faster searching. Handy, eh?

The Guru
June 05, 2000
Posted from Microsoft Site

Creating multiple controls of the same type 

You can [Ctrl] your Visual Basic control selection. 

Suppose you want to place several radio buttons within a frame on a Visual Basic form. If you click on the Radio Button control in the palette, then draw your button, the palette selection will automatically revert to the pointer. To circumvent this behavior, press and hold [Ctrl] while you click on the control in the palette. Now the control remains selected, so you can click and drag as many radio buttons (or any other control type) as you need. When you're finished, click on the pointer in the palette to return to the normal mode of operation. 

 

The Guru
June 04, 2000
Posted from Microsoft Windows2000 Site

Move Portions of Your Start Menu in W2K

You can make shortcuts on the taskbar that bring up frequently used items from your Start menu. This is also helpful if you want easy access to Start menu items on a different part of the screen.

  1. Right click on an empty section of the taskbar point to Toolbars and then click New Toolbar... 
  2. In the New Toolbar window, browse to your Start menu directory (c:\documents and settings\USERNAME\Start Menu\Programs\). Choose the folder you want. Click on OK. 
  3. Rearrange your taskbar by dragging on the vertical bars until only the folder title is showing. All the actual links will disappear into a double arrow. 
  4. Click the double arrow to bring up the menu. You can drag the menu to another edge of the display to act as a second Start menu. For long titles, you might want to rename them to something shorter before you create the shortcut. 
The Guru
June 04, 2000

Using Microsoft's HTML Parser to Get Data from Web Sites

This article describes how to gather information from the Web and distribute it on other Web pages or databases with the help of the reusable parser component of Internet Explorer. (7 printed pages)

Click Here To Read Whole Article

 
The Guru.
May 30, 2000
Posted From Microsoft Site

Spell check RTF documents in Visual Basic

To spell check RTF documents, you could resort to embedding Word into your application. However, if you plan to use the WebBrowser control, there's no need to program Word for spell checking. That's because the WebBrowser control provides this functionality for you. To access it, you use the WebBrowser control's ExecWB() method with the OLECMDID_SPELL flag.
To illustrate, add the WebBrowser control to a form, then add the following code to the form's Load() event:
WebBrowser1.Navigate "D:\Internet\spell.rtf" Replace the path with any string that points to an RTF file.
Next, add a command button, and enter this code in its Click() event:
WebBrowser1.ExecWB OLECMDID_SPELL, OLECMDEXECOPT_DODEFAULT
Run the project. The WebBrowser displays the RTF file, and when you click the command button, VB runs through the normal spell check operation.

 

Add Your VB Tip

Please provide the following contact information:

First Name
Last Name
E-mail

Enter your VB Tip in the space provided below.

 

 

 

Send mail to WebMaster with questions or comments about this web site.
This website is best viewed with a screen resolution of 800*600 or better.
This website is optimized for Microsoft Internet Explorer 6.x
K&K Consulting, Proud to be a Microsoft Business Partner.
Last modified: January 31, 2002