• 0

VB.Net OwnerDrawn menus tutorial


Question

Some of you have asked me how to create your own OwnerDrawn menus.

Since finding info on how to create my own menus was very hard, and I had tried everywhere (maybe i'm just dumb or unlucky..) and found nearly nothing, here is my tutorial. I hope you enjoy it!

This tutorial is NOT complete, so don't complain about it... I expect to complete it today or tomorrow, but decided to post what I already have so you can learn something, search the web or MSDN for it and maybe, who knows, you won't need the rest of the tutorial at all!

Request: Please DO post any errors you have found or any suggestions you have. If you can explain something better than me, please send me a PM with it and I will add it to this post and give you credit for it.

Also, if you want to, post screenshots of your own menus!

So.. here we go!

Understanding how Inheritance works

The first thing you need to understand is how Inheritance works in .Net.

Imagine this. You buy a brand new car. It has everything you need, so you use it as it is. But time goes by and you find you need somethings the car as it is can't give you, maybe you need a radio and a GPS or you feel you need to completely change the looks of the car.

To do this, you have two options:

  • You create your own car from scratch adding exactly what you want and how you want it
  • You take the car you have which already has most of what you need and simply change it

Which option do you think is the best? With the first you have to recreate most of what you already have and which is want you want. The car you have already has seats, wheels, direction, engine, etc. So why recreate all that?

With the second options, however, this is solved. You use want you want from the car, and create ONLY what the car does not give you.

This is what inheritance is all about. You take something with basic functionality and you take it from there, adding or changing things as you please.

Indeed, when you create a new windows form, the first lines of code are

Public Class Form1
    Inherits System.Windows.Forms.Form

The first line says you are creating a new class called Form1, and the second line says that class inherits from System.Windows.Forms.Form. That is to say, the basic funcionality of the form is already there (like the title bar and the minimize, maximize and close buttons and the area where you place your controls) and you just have to build upon it.

The same happens when you create your own menuitem. The basic funcionality, like controling the mouseovers and click and etc are alredy in the Mouseitem class. If you inherit it, you won't have to do it all through Windows APIs and your work is greatly simplified.

I could have easily skipped this and you would not lose much, but I preferred to add it so you can understand better how the whole thing works.

So, the first step to create your own menus is a very simple one: Create a new class and inherit from the MenuItem class.

So, create a Windows Forms project in Visual Basic. Add a new class to it. Finally inherit from the MenuItem class! Simple, isn't it?

You can also create a separate project so you can create a .Net Component and use those menus in different projects, but i'll cover that later on.

So far, your code should be something like

Public Class Menu1
    Inherits System.Windows.Forms.MenuItem

Beeing, of course, Menu1 the name you want to give your own menus.

The basics of Ownerdrawn menus I - OnMeasureItem

Now that your class is created, you need to understand the basics of the Ownerdrawn menus.

One thing can easily see when using any application it that different menus have almost always different heights and different widths. That is to say, a menu with three items has a smaller witdh than a menu with 10 items, and that "this is my very long menu caption" and "file" would produce menus with very different widths.

So, before drawing your menu you have to measure it so that Windows can create the canvas where you will draw.

The measure is done overridding OnMeasureItem.

So, place the following code on your class.

Protected Overrides Sub OnMeasureItem(ByVal e As System.Windows.Forms.MeasureItemEventArgs)

End Sub

(This is the same as chosing "(Overrides)" from the left drop down list and then chosing "OnMeasureItem" from the right drop down list)

As you can see, that sub has one parameter, e. It is through e that the measurement will be made. e has two properties, ItemHeight and ItemWidth, and it is by setting their values that the blank are where you draw will be created. It sums the Height of all the items and uses the width of the longest item.

However, these values will depend of several things, like how you wish to draw your menus (if you wish to add an icon you have to leave space for it, for instance) or the font you use.

I, for one, think it is best to create a Font variable in the class where you set the font you want to use. That way, you only have to change the code on one single place if you wish to change the font later on, and you can even create a property so you can change the code from VS.net IDE or at run time.

To create this variable, just type (outside of any "sub", of course...)

Dim myFont As Font

myFont being the name of the variable. And don't forget to set the font...

Now you need to check the lenght and width of the text using that font. If a font has size 8, it is smaller than a size 20 font.

So, a possibility for this would be

           e.ItemHeight = CInt(e.Graphics.MeasureString(MyBase.Text, myFont, 10000).Height) + 4
            e.ItemWidth = CInt(e.Graphics.MeasureString(MyBase.Text, myFont, 10000).Width) + 5
            If Me.MenuItems.Count > 0 Then e.ItemWidth += 10

The MeasureString method returns the width and heigth of the rectangle containg a specific string, using a specific font. The last line checks if the MenuItem beeing measured has any child menuitems, and if so it adds 10 pixels to its width so there is space for the arrow to be drawn. If you go to the "File" menu in Windows Explorer, you will see that the "New" item has an arrow and that if you hover it, a new menu will appear. This is what I am referring to.

The basics of Ownerdrawn menus II - OnDrawItem

Now that you have the items measured, you need to draw them, which is done overriding the OnDrawItem sub.

So you should add a new sub, as shown below.

   Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)

    End Sub

The drawing is handled one menu item at a time. So, if you have four menu items, for instance, "New", "Open", "Save" and "Close", this method will be called for each and every one of those items as each item has its own rectangle.

Remember the "e" object used in the OnMeasureItem? It will be used here as well, but for a different purpose. Here you use it to retreave the bounds of the item's rectangle and to draw to that rectangle using the "e"'s graphics object.

A simple way to draw the item's text to the rectangle would be

       MyBrush = New SolidBrush(Color.Green)
        e.Graphics.DrawString(Me.Text, Myfont, MyBrush, e.Bounds.X + 2, e.Bounds.Y + 2)

MyBrush is a new global variable I created. It is advisable to create brushes,pens, etc as global variables instead of creating new objects inside the sub.

Are you ready to test your menus? Here we go!

The basics of Ownerdrawn menus III - Using them on a form

Create a new form and add a new menus to it. Now go to code view and change all references to Windows.Forms.Windows.MenuItem to (your name here).

So if your class is named "MyMenu", you would have

   Friend WithEvents MenuItem2 As MyMenu
    Friend WithEvents MenuItem3 As MyMenu
    Friend WithEvents MenuItem4 As MyMenu
(...)
        Me.MenuItem2 = New MyMenu
        Me.MenuItem3 = New MyMenu
        Me.MenuItem4 = New MyMenu

Run your project. Open the menu and... nothing happens!

So what have you done wrong? Absolutely nothing.

You simply have to set the menu's "Ownerdraw" property to true. While this can be done in the IDE one menuitem at a time, there is a more efficient and quick way.

You simply use the "New" sub to set the menu item to Ownerdraw = true and to set a default font (or else the Myfont object is set to nothing and your program will crash).

   Public Sub New()
        MyBase.OwnerDraw = True
        Myfont = New Font("Comic Sans MS", 12)
    End Sub

If you run your program now, the menus will work. However, there are two problems.

  • The menu item displayed in the form is drawn as if it was in the sub menu
  • When the mouse hovers the menu items, they don't change

These are very easy to fix, and that's what we will do now

(to be continued)

Andr? Nogueira

Edited by anog
Link to comment
https://www.neowin.net/forum/topic/194617-vbnet-ownerdrawn-menus-tutorial/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Hi there! I just got back from vacations :cool:

So, I'd like to know if u want me to continue this tutorial or not! Like, is it good? is it worth reading?

If you've come across a page with a similar but better tutorial, just post it here and I'll link to it.

Thanks!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft 365 Word gets SharePoint eSignature, now you can ditch third-party signing tools by Paul Hill Microsoft has just announced that it will be rolling out an extremely convenient feature for Microsoft 365 customers who use Word throughout this year. The Redmond giant said that you’ll now be able to use SharePoint’s native eSignature service directly in Microsoft Word. The new feature allows customers to request electronic signatures without converting the documents to a PDF or leaving the Word interface, significantly speeding up workflows. Microsoft’s integration of eSignatures also allows you to create eSignature templates which will speed up document approvals, eliminate physical signing steps, and help with compliance and security in the Microsoft 365 environment. This change has the potential to significantly improve the quality-of-life for those in work finding themselves adding lots of signatures to documents as they will no longer have to export PDFs from Word and apply the signature outside of Word. It’s also key to point out that this feature is integrated natively and is not an extension. The move is quite clever from Microsoft, if businesses were using third-party tools to sign their documents, they would no longer need to use these as it’s easier to do it in Word. Not only does it reduce reliance on other tools, it also makes Microsoft’s products more competitive against other office suites such as Google Workspace. Streamlined, secure, and compliant The new eSignature feature is tightly integrated into Word. It lets you insert signature fields seamlessly into documents and request other people’s signatures, all while remaining in Word. The eSignature feature can be accessed in Word by going to the Insert ribbon. When you send a signature request to someone from Word, the recipient will get an automatically generated PDF copy of the Word document to sign. The signed PDF will then be kept in the same SharePoint location as the original Word file. To ensure end-to-end security and compliance, the document never leaves the Microsoft 365 trust boundary. For anyone with a repetitive signing process, this integration allows you to turn Word documents into eSignature templates so they can be reused. Another feature that Microsoft has built in is audit trail and notifications. Both the senders and signers will get email notifications throughout the entire signing process. Additionally, you can view the activity history (audit trail) in the signed PDF to check who signed it and when. Finally, Microsoft said that administrators will be able to control how the feature is used in Word throughout the organization. They can decide to enable it for specific users via an Office group policy or limit it to particular SharePoint sites. The company said that SharePoint eSignature also lets admins log activities in the Purview Audit log. A key security measure included by Microsoft, which was mentioned above, was the Microsoft 365 trust boundary. By keeping documents in this boundary, Microsoft ensures that all organizations can use this feature without worry. The inclusion of automatic PDF creation is all a huge benefit to users as it will cut out the step of manual PDF creation. While creating a PDF isn’t complicated, it can be time consuming. The eSignature feature looks like a win-win-win for organizations that rely on digital signatures. Not only does it speed things along and remain secure, but it’s also packed with features like tracking, making it really useful and comprehensive. When and how your organization gets it SharePoint eSignature has started rolling out to Word on the M365 Beta and Current Channels in the United States, Canada, the United Kingdom, Europe, and Australia-Pacific. This phase of the rollout is expected to be completed by early July. People in the rest of the world will also be gaining this time-saving feature but it will not reach everyone right away, though Microsoft promises to reach everybody by the end of the year. To use the feature, it will need to be enabled by administrators. If you’re an admin who needs to enable this, just go to the M365 Admin Center and enable SharePoint eSignature, ensuring the Word checkbox is selected. Once the service is enabled, apply the “Allow the use of SharePoint eSignature for Microsoft Word” policy. The policy can be enabled via Intune, Group Policy manager, or the Cloud Policy service for Microsoft 365 Assuming the admins have given permission to use the feature, users will be able to access SharePoint eSignatures on Word Desktop using the Microsoft 365 Current Channel or Beta Channel. The main caveats include that the rollout is phased, so you might not get it right away, and it requires IT admins to enable the feature - in which case, it may never get enabled at all. Overall, this feature stands to benefit users who sign documents a lot as it can save huge amounts of time cumulatively. It’s also good for Microsoft who increase organizations’ dependence on Word.
    • It's always good to have an option to secure your stuff to another medium. I did that with DVD/CD collection, and run my own media server now. It's more convenient that way and no need for separate players anymore.
    • Google Search AI Mode gets support for data visualization and custom charts by Aditya Tiwari Google announced it is rolling out support for data visualizations and graphs for finance-related queries in Google Search's AI Mode. Introduced last month at the Google I/O 2025 keynote, the feature lets you analyze complex datasets and create custom charts simply using natural language prompts. The updated AI Mode lets you compare and analyze information over a specific period, Google explained. It generates interactive graphs and provides a comprehensive explanation for your questions. AI Mode utilizes Gemini's multimodal capabilities and multi-step reasoning approach to comprehend the question's intent while accessing historical and real-time information relevant to the question. For instance, instead of manually researching individual companies and their stock prices, you can use AI Mode to compare the stock performance of different companies for a specific year. Once the graph is generated, you can choose the desired time period using the mouse cursor and ask follow-up questions based on the data presented. These new data visualizations for finance queries are available to users who have enabled the AI Mode experiment in Labs. AI Mode was introduced earlier this year as an experimental feature in the US. The feature is an upgraded version of AI Overviews, and Google closely worked with AI power users through the initial development process. It uses the “query fan-out” technique to perform multiple related searches across subtopics and different data sources, then combines them to come up with a comprehensive response. Google updated AI Mode last month to use a custom version of the latest Gemini 2.5 model. It added several new features, including Deep Search, live capabilities, agentic capabilities of Project Mariner, a new shopping experience, and the ability to add personal context by linking Google apps. The search giant is planning to turn AI Mode into its bread and butter. It has begun testing ads for the feature, which will appear below and be integrated into AI Mode responses where relevant.
    • Guys, you should find another way to promote your deals... It's the third article in the last months that promote this deal for an upgrade from 10. Considering that upgrade from 10 to 11 is free it's a total non-sense.
    • Store should be a shrine of useful applications, vetted and verified. Easily sorted by publisher. Windows should start with not much installed and have things as options in the store. Not the wild west mess that it is. You could delete 95%+ of the crap on there and no one would notice. They need to add a better UI to the updates, it's awful right now.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      432
    2. 2
      +FloatingFatMan
      239
    3. 3
      snowy owl
      213
    4. 4
      ATLien_0
      211
    5. 5
      Xenon
      157
  • Tell a friend

    Love Neowin? Tell a friend!