Visual Basic.NET
  Home arrow Visual Basic.NET arrow Page 4 - Focusing on Forms and Menus in Visual Basi...
Iron Speed
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Download TestComplete 
Windows Web Hosting
 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
VISUAL BASIC.NET

Focusing on Forms and Menus in Visual Basic
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 9
    2007-03-01

    Table of Contents:
  • Focusing on Forms and Menus in Visual Basic
  • 4.16 Creating a Fading Form
  • 4.17 Creating a Nonrectangular Form
  • 4.18 Changing Menus at Runtime
  • 4.19 Creating Shortcut Menus

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Focusing on Forms and Menus in Visual Basic - 4.18 Changing Menus at Runtime
    (Page 4 of 5 )

    Problem

    You want to customize the menu structure in your main form at runtime. The structure should be based on settings made available by some user-configurable method.

    Solution

    Sample code folder: Chapter 04\RuntimeMenus

    The menu-specific classes included in the Windows Forms library can be created at either design time or runtime. This recipe’s code adds a basic menu to a form at design time and enhances it at runtime by adding the user’s Internet Explorer “Favorites” to one of the menus.

    Create a new Windows Forms application, and add aMenuStripcontrol namedMainMenuto the form. Perform the following actions on this menu:

    1. Add a top-level menu namedMenuFile, using&Filefor itsTextproperty.
    2. Add a top-level menu namedMenuFavorites, usingFa&voritesfor itsTextproperty.
    3. Add a menu item namedMenuExitProgramthat is subordinate toMenuFile, usingE&xitfor itsTextproperty. Set itsShortcutKeysproperty toAlt+F4.
    4. Add a menu item namedMenuNoFavoritesthat is subordinate toMenuFavorites, using(empty)for itsTextproperty. Set itsEnabledproperty toFalse.

    Figure 4-19 shows a partial look at this form’s menu structure in design mode.


    Figure 4-19.  The initial menus for the runtime menu sample

    Next, replace the form’s code template with the following code. I’ve highlighted the lines that do the actual adding of menu items:

      Imports MVB = Microsoft.VisualBasic

      Public Class Form1
        
    Private Declare Auto Function GetPrivateProfileString_
            Lib "kernel32" _
            (ByVal AppName As String, _
           
    ByVal KeyName As String, _
            ByVal DefaultValue As String, _
            ByVal ReturnedString As System.Text.StringBuilder, _
            ByVal BufferSize As Integer, _
            ByVal FileName As String) As Integer

         Private Sub MenuExitProgram_Click( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs) _
               Handles MenuExitProgram.Click
            
    ' ----- Exit the program.
            Me.Close()
         End Sub

         Private Sub Form1_Load(ByVal sender As Object, _
              
    ByVal e As System.EventArgs) Handles Me.Load
            ' ----- Scan through the user's "Favorites" and
            '       add them as menu items.
            Dim favoritesPath As String

            ' ----- Determine the location of the "Favorites"
            '       folder.
            favoritesPath = Environment.GetFolderPath( _ 

            Environment.SpecialFolder.Favorites)
            If (favoritesPath = "") Then Return
            If (My.Computer.FileSystem.DirectoryExists( _
               favoritesPath) = False) Then Return

            ' ----- Call the recursive routine that builds the menu.
            BuildFavorites(MenuFavorites, favoritesPath)

            ' ----- If favorites were added, hide the
            '       "no favorites" item.
            If (MenuFavorites.DropDownItems.Count > 1) Then _ 
             
    MenuNoFavorites.Visible = False  
         End Sub

         Private Sub BuildFavorites(ByVal whichMenu As _
              
    ToolStripMenuItem, ByVal fromPath As String)
            ' ----- Given a starting directory, add all files
            '       and directories in it to the specified menu.
            '       Recurse for suborindate directories.
            Dim oneEntry As String
            Dim menuEntry As ToolStripMenuItem
            Dim linkPath As String
            Dim displayName As String

            ' ----- Start with any directories.
            For Each oneEntry In My.Computer.FileSystem. _
                 
    GetDirectories(fromPath)
               ' ----- Create the parent menu, but don't
               '       attach it yet.
              
    menuEntry = New ToolStripMenuItem( _ 
             My.Computer.FileSystem.GetName(oneEntry))

               ' ----- Recurse to build the sub-directory branch.
               BuildFavorites(menuEntry, oneEntry)
     

               ' ----- If that folder contained items,
               '       then attach it.
              If (menuEntry.DropDownItems.Count > 0) Then _
               whichMenu.DropDownItems.Add(menuEntry) 
           Next oneEntry 

           ' ---- Next, build the actual file links. Only
           '      look at ".url" files.
           For Each oneEntry In My.Computer.FileSystem. _
                
    GetFiles(fromPath, FileIO.SearchOption. _
                
    SearchTopLevelOnly, "*.url")
              ' ----- Build a link based on this file. These
              '       files are old-style INI files.
              linkPath = GetINIEntry("InternetShortcut", _
                 "URL", oneEntry)
             
    If (linkPath <> "") Then
                 ' ----- Found the link. Add it to the menu.
                 displayName = My.Computer.FileSystem. _
                   
    GetName(oneEntry)
                 displayName = MVB.Left(displayName, _
                    displayName.Length - 4)

               menuEntry = New ToolStripMenuItem(displayName)
                menuEntry.Tag = linkPath
               
    whichMenu.DropDownItems.Add(menuEntry)

                ' ----- Connect this entry to the event handler.
                AddHandler menuEntry.Click, _
                   AddressOf RunFavoritesLink
             End If
          Next oneEntry
       End Sub

       Private Sub RunFavoritesLink( _
             ByVal sender As System.Object, _
             ByVal e As System.EventArgs)
         
    ' ----- Run the link.
          Dim whichMenu As ToolStripMenuItem

          whichMenu = CType(sender, ToolStripMenuItem)
          Process.Start(whichMenu.Tag)
       End Sub

       Private Function GetINIEntry(ByVal sectionName As String, _
             ByVal keyName As String, _
             ByVal whichFile As String) As String
         
    ' ----- Extract a value from an INI-style file.
          Dim resultLength As Integer
          Dim targetBuffer As New System.Text.StringBuilder(500)

          resultLength = GetPrivateProfileString(sectionName, _
             keyName, "", targetBuffer, targetBuffer.Capacity, _

             whichFile)
         
    Return targetBuffer.ToString()
       
    End Function
     
    End Class

    Run the program, and access its Favorites menu to browse and open the current user’s Internet Explorer favorites.

    Discussion

    The bulk of this recipe’s code deals with scanning through a directory structure and examining each file and subdirectory. Most of the files in the “Favorites” folder have a .url extension and contain data in an “INI file” format.

    Here’s a sample link to a popular search engine:

      [DEFAULT]
      BASEURL=http://www.google.com/
      [InternetShortcut]
      URL=http://www.google.com/

    The last “URL=” line provides the link we need to enable favorites support in our program.

    The important part of the program is the building of the menu structure. Each menu item attached to the form’s main menuMenuStrip control is a relatedToolStripMenuItemclass instance. These can be attached to the menu at any time through itsDropDownItemscollection. Each menu item in turn has its ownDropDownItemscollection that manages subordinate menu items.

    To make each new menu item do something, as you add them, connect them to the previously writtenRunFavoritesLinkmethod:

      AddHandler menuEntry.Click, AddressOf RunFavoritesLink

    More Visual Basic.NET Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Visual Basic 2005 Cookbook," published by...
     

    Buy this book now. This article is excerpted from chapter four of the Visual Basic 2005 Cookbook, written by Tim Patrick and John Clark Craig (O'Reilly; ISBN: 0596101775). Check it out today at your favorite bookstore. Buy this book now.

    VISUAL BASIC.NET ARTICLES

    - Types of Operators in Visual Basic
    - Operators
    - Understanding Custom Events using Visual Bas...
    - Polymorphism using Abstract Classes in Visua...
    - Shadowing using Shadows in Visual Basic.NET ...
    - Overloading and Overriding in Visual Basic.N...
    - More on Controlling Windows Fax Services Usi...
    - Programmatically Controlling Windows Fax Ser...
    - Focusing on Forms and Menus in Visual Basic
    - Manipulating Forms with the Windows Forms Li...
    - Basics of the Windows Forms Library
    - Forms, Controls, and Other Useful Objects
    - Implementing OOP to Develop Database Oriente...
    - Using Themes and Skins for Personalization w...
    - A Deeper Look at Personalization using Visua...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway