vb.netcontextmenutoolstripmenutoolstripdropdown

Cant load image in context menu as icon


I am trying to use the code from the following link:

VB- Helper Create menu items at run time with images, shortcut keys, and event handlers in Visual Basic .NET

The only difference is that I want a local image and not one from my.Recources

What I have is the following:

    ''Tool 2 displays a string and image.
    Dim tool2 As New ToolStripMenuItem("Tool 2", (Image.FromFile("C:\test\icon.jpg")))
    tool2.Name = "mnuToolsTool2"
    tool2.ShortcutKeys = (Keys.D2 Or Keys.Control) ' Ctrl+2
    AddHandler tool2.Click, AddressOf mnuTool2_Click
    ToolStripMenuItem1.DropDownItems.Add(tool2)

Solution

  • I could not reproduce this "error". However, from the given text, code and link, my best guess is as follows:

    1. You are using a 64 bit machine.
    2. You run the code inside the Form.Load event.
    3. An error occurs somewhere in this method.

    Private Sub _Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Code...
        Throw New Exception("ooops..")
        'Code...
    End Sub
    

    As you might not know is that errors thrown in the Form.Load on a 64 bit machine are "swallowed" by the system.

    For more information, read this SO post: Why the form load can't catch exception?

    You should move your code inside the constructor:

    Public Sub New()
        Me.InitializeComponent()
        'Code goes here...
    End Sub
    

    Or change to the Form.Shown event:

    Private Sub _Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        Try
            'Code goes here...
        Catch ex As Exception
            MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub