VB.NET equivalent of CommandBars [duplicate] - vb.net

This question already has answers here:
How to create a popup menu in visual basic.net?
(2 answers)
Closed 5 years ago.
I have this code in VBA (shown in a simplified version) :
Sub TheMenu()
Dim Obj As CommandBar
Set Obj = Application.CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
Obj.Controls.Add(Type:=msoControlButton).Caption = "Button1"
Obj.Controls.Add(Type:=msoControlButton).Caption = "Button2"
Obj.ShowPopup
End Sub
I wish to make something equivalent (meaning "that looks similar and has similar uses", I don't need more) in VB.NET. Do you know any way of doing so?
I am using in VS2015, a "Windows Forms application" project using .NET framework 4.6.1 .

You can follow the example bellow here:
Public Class Connect
Implements Extensibility.IDTExtensibility2
Implements IDTCommandTarget
Private Const MY_COMMAND_NAME As String = "MyCommand"
Private applicationObject As EnvDTE.DTE
Private addInInstance As EnvDTE.AddIn
Private myStandardCommandBarControl As CommandBarControl
Private myToolsCommandBarControl As CommandBarControl
Private myCodeWindowCommandBarControl As CommandBarControl
Private myTemporaryToolbar As CommandBar
Private myTemporaryCommandBarPopup As CommandBarPopup
Public Sub OnConnection(ByVal application As Object, ByVal connectMode _
As Extensibility.ext_ConnectMode, ByVal addInInst As Object, _
ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection
Dim myCommand As Command
Dim standardCommandBar As CommandBar
Dim menuCommandBar As CommandBar
Dim toolsCommandBar As CommandBar
Dim codeCommandBar As CommandBar
Dim toolsCommandBarControl As CommandBarControl
Dim myCommandBarButton As CommandBarButton
Dim position As Integer
Try
applicationObject = CType(application, EnvDTE.DTE)
addInInstance = CType(addInInst, EnvDTE.AddIn)
Select Case connectMode
Case ext_ConnectMode.ext_cm_AfterStartup, ext_ConnectMode.ext_cm_Startup
' Try to retrieve the command, just in case it was already created
Try
myCommand = applicationObject.Commands.Item(addInInstance.ProgID & "." & "MyCommand")
Catch
End Try
' Add the command if it does not exists
If myCommand Is Nothing Then
myCommand = applicationObject.Commands.AddNamedCommand(addInInstance, _
"MyCommand", "MyCommand", "Executes the command for MyAddin", True, 59, Nothing, _
vsCommandStatus.vsCommandStatusSupported Or vsCommandStatus.vsCommandStatusEnabled)
End If
' Retrieve some built-in command bars
standardCommandBar = applicationObject.CommandBars.Item("Standard")
menuCommandBar = applicationObject.CommandBars.Item("MenuBar")
toolsCommandBar = applicationObject.CommandBars.Item("Tools")
codeCommandBar = applicationObject.CommandBars.Item("Code Window")
' Add a button to the built-in "Standard" toolbar
myStandardCommandBarControl = myCommand.AddControl(standardCommandBar, _
standardCommandBar.Controls.Count + 1)
myStandardCommandBarControl.Caption = MY_COMMAND_NAME
' Change the button style, which must be done casting the control to a button
myCommandBarButton = DirectCast(myStandardCommandBarControl, CommandBarButton)
myCommandBarButton.Style = MsoButtonStyle.msoButtonIcon
' Add a button to the built-in "Tools" menu
myToolsCommandBarControl = myCommand.AddControl(toolsCommandBar, toolsCommandBar.Controls.Count + 1)
myToolsCommandBarControl.Caption = MY_COMMAND_NAME
' Add a button to the built-in "Code Window" context menu
myCodeWindowCommandBarControl = myCommand.AddControl(codeCommandBar, codeCommandBar.Controls.Count + 1)
myCodeWindowCommandBarControl.Caption = MY_COMMAND_NAME
' Add a new toolbar with a button on it
myTemporaryToolbar = applicationObject.CommandBars.Add("MyTemporaryToolbar", _
MsoBarPosition.msoBarTop, System.Type.Missing, True)
' Change the button style, which must be done casting the control to a button
myCommandBarButton = DirectCast(myCommand.AddControl(myTemporaryToolbar), CommandBarButton)
myCommandBarButton.Style = MsoButtonStyle.msoButtonIcon
' Make visible the toolbar
myTemporaryToolbar.Visible = True
' Calculate the position of a new command bar popup by the "Tools" menu
toolsCommandBarControl = DirectCast(toolsCommandBar.Parent, CommandBarControl)
position = toolsCommandBarControl.Index + 1
' Add a new command bar popup with a button on it
myTemporaryCommandBarPopup = DirectCast(menuCommandBar.Controls.Add( _
MsoControlType.msoControlPopup, System.Type.Missing, System.Type.Missing, _
position, True), CommandBarPopup)
myTemporaryCommandBarPopup.CommandBar.Name = "MyTemporaryCommandBarPopup"
myTemporaryCommandBarPopup.Caption = "My menu"
myCommand.AddControl(myTemporaryCommandBarPopup.CommandBar)
myTemporaryCommandBarPopup.Visible = True
End Select
Catch e As System.Exception
System.Windows.Forms.MessageBox.Show(e.ToString)
End Try
End Sub
Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, _
ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection
Try
If Not (myStandardCommandBarControl Is Nothing) Then
myStandardCommandBarControl.Delete()
End If
If Not (myCodeWindowCommandBarControl Is Nothing) Then
myCodeWindowCommandBarControl.Delete()
End If
If Not (myToolsCommandBarControl Is Nothing) Then
myToolsCommandBarControl.Delete()
End If
If Not (myTemporaryToolbar Is Nothing) Then
myTemporaryToolbar.Delete()
End If
If Not (myTemporaryCommandBarPopup Is Nothing) Then
myTemporaryCommandBarPopup.Delete()
End If
Catch e As System.Exception
System.Windows.Forms.MessageBox.Show(e.ToString)
End Try
End Sub
Public Sub OnBeginShutdown(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnBeginShutdown
End Sub
Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnAddInsUpdate
End Sub
Public Sub OnStartupComplete(ByRef custom As System.Array) Implements _
Extensibility.IDTExtensibility2.OnStartupComplete
End Sub
Public Sub Exec(ByVal cmdName As String, ByVal executeOption As vsCommandExecOption, _
ByRef varIn As Object, ByRef varOut As Object, ByRef handled As Boolean) Implements IDTCommandTarget.Exec
handled = False
If (executeOption = vsCommandExecOption.vsCommandExecOptionDoDefault) Then
If cmdName = addInInstance.ProgID & "." & MY_COMMAND_NAME Then
handled = True
System.Windows.Forms.MessageBox.Show("Command executed.")
End If
End If
End Sub
Public Sub QueryStatus(ByVal cmdName As String, ByVal neededText As vsCommandStatusTextWanted, _
ByRef statusOption As vsCommandStatus, ByRef commandText As Object) Implements IDTCommandTarget.QueryStatus
If neededText = EnvDTE.vsCommandStatusTextWanted.vsCommandStatusTextWantedNone Then
If cmdName = addInInstance.ProgID & "." & MY_COMMAND_NAME Then
statusOption = CType(vsCommandStatus.vsCommandStatusEnabled + _
vsCommandStatus.vsCommandStatusSupported, vsCommandStatus)
Else
statusOption = vsCommandStatus.vsCommandStatusUnsupported
End If
End If
End Sub
End Class

Related

Radio button on the ContextMenu or ContextMenuStrip [winforms]

I am searching for the way to implement a context menu item with radio button appearance like this: Windows 7's ContextMenu with RadioButton menu item
I have search through Google and SO, this post Adding RadioButtons to ContextMenu is close, but it's related to Java, and I am looking for a control or renderer in .NET for winforms.
Any solution or suggestion would be great help. Thank you.
Option buttons, also known as radio buttons, are similar to check boxes except that users can select only one at a time. Although by default the ToolStripMenuItem class does not provide option-button behavior, the class does provide check-box behavior that you can customize to implement option-button behavior for menu items in a MenuStrip control.
When the CheckOnClick property of a menu item is true, users can click the item to toggle the display of a check mark. The Checked property indicates the current state of the item. To implement basic option-button behavior, you must ensure that when an item is selected, you set the Checked property for the previously selected item to false.
The following procedures describe how to implement this and additional functionality in a class that inherits the ToolStripMenuItem class. The ToolStripRadioButtonMenuItem class overrides members such as OnCheckedChanged and OnPaint to provide the selection behavior and appearance of option buttons. Additionally, this class overrides the Enabled property so that options on a submenu are disabled unless the parent item is selected.
First Create a Class for RadioButton
This is combination of RadioButton and ToggleButton.
Public Class ToolStripRadioButtonMenuItem
Inherits ToolStripMenuItem
Public Sub New()
MyBase.New()
Initialize()
End Sub
Public Sub New(ByVal text As String)
MyBase.New(text, Nothing, CType(Nothing, EventHandler))
Initialize()
End Sub
Public Sub New(ByVal image As Image)
MyBase.New(Nothing, image, CType(Nothing, EventHandler))
Initialize()
End Sub
Public Sub New(ByVal text As String, ByVal image As Image)
MyBase.New(text, image, CType(Nothing, EventHandler))
Initialize()
End Sub
Public Sub New(ByVal text As String, _
ByVal image As Image, ByVal onClick As EventHandler)
MyBase.New(text, image, onClick)
Initialize()
End Sub
Public Sub New(ByVal text As String, ByVal image As Image, _
ByVal onClick As EventHandler, ByVal name As String)
MyBase.New(text, image, onClick, name)
Initialize()
End Sub
Public Sub New(ByVal text As String, ByVal image As Image, _
ByVal ParamArray dropDownItems() As ToolStripItem)
MyBase.New(text, image, dropDownItems)
Initialize()
End Sub
Public Sub New(ByVal text As String, ByVal image As Image, _
ByVal onClick As EventHandler, ByVal shortcutKeys As Keys)
MyBase.New(text, image, onClick)
Initialize()
Me.ShortcutKeys = shortcutKeys
End Sub
' Called by all constructors to initialize CheckOnClick.
Private Sub Initialize()
CheckOnClick = True
End Sub
Protected Overrides Sub OnCheckedChanged(ByVal e As EventArgs)
MyBase.OnCheckedChanged(e)
' If this item is no longer in the checked state, do nothing.
If Not Checked Then Return
' Clear the checked state for all siblings.
For Each item As ToolStripItem In Parent.Items
Dim radioItem As ToolStripRadioButtonMenuItem = _
TryCast(item, ToolStripRadioButtonMenuItem)
If radioItem IsNot Nothing AndAlso _
radioItem IsNot Me AndAlso _
radioItem.Checked Then
radioItem.Checked = False
' Only one item can be selected at a time,
' so there is no need to continue.
Return
End If
Next
End Sub
Protected Overrides Sub OnClick(ByVal e As EventArgs)
' If the item is already in the checked state, do not call
' the base method, which would toggle the value.
If Checked Then Return
MyBase.OnClick(e)
End Sub
' Let the item paint itself, and then paint the RadioButton
' where the check mark is displayed, covering the check mark
' if it is present.
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
MyBase.OnPaint(e)
' If the client sets the Image property, the selection behavior
' remains unchanged, but the RadioButton is not displayed and the
' selection is indicated only by the selection rectangle.
If Image IsNot Nothing Then Return
' Determine the correct state of the RadioButton.
Dim buttonState As RadioButtonState = RadioButtonState.UncheckedNormal
If Enabled Then
If mouseDownState Then
If Checked Then
buttonState = RadioButtonState.CheckedPressed
Else
buttonState = RadioButtonState.UncheckedPressed
End If
ElseIf mouseHoverState Then
If Checked Then
buttonState = RadioButtonState.CheckedHot
Else
buttonState = RadioButtonState.UncheckedHot
End If
Else
If Checked Then buttonState = RadioButtonState.CheckedNormal
End If
Else
If Checked Then
buttonState = RadioButtonState.CheckedDisabled
Else
buttonState = RadioButtonState.UncheckedDisabled
End If
End If
' Calculate the position at which to display the RadioButton.
Dim offset As Int32 = CInt((ContentRectangle.Height - _
RadioButtonRenderer.GetGlyphSize( _
e.Graphics, buttonState).Height) / 2)
Dim imageLocation As Point = New Point( _
ContentRectangle.Location.X + 4, _
ContentRectangle.Location.Y + offset)
' If the item is selected and the RadioButton paints with partial
' transparency, such as when theming is enabled, the check mark
' shows through the RadioButton image. In this case, paint a
' non-transparent background first to cover the check mark.
If Checked AndAlso RadioButtonRenderer _
.IsBackgroundPartiallyTransparent(buttonState) Then
Dim glyphSize As Size = RadioButtonRenderer _
.GetGlyphSize(e.Graphics, buttonState)
glyphSize.Height -= 1
glyphSize.Width -= 1
Dim backgroundRectangle As _
New Rectangle(imageLocation, glyphSize)
e.Graphics.FillEllipse( _
SystemBrushes.Control, backgroundRectangle)
End If
RadioButtonRenderer.DrawRadioButton( _
e.Graphics, imageLocation, buttonState)
End Sub
Private mouseHoverState As Boolean = False
Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs)
mouseHoverState = True
' Force the item to repaint with the new RadioButton state.
Invalidate()
MyBase.OnMouseEnter(e)
End Sub
Protected Overrides Sub OnMouseLeave(ByVal e As EventArgs)
mouseHoverState = False
MyBase.OnMouseLeave(e)
End Sub
Private mouseDownState As Boolean = False
Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
mouseDownState = True
' Force the item to repaint with the new RadioButton state.
Invalidate()
MyBase.OnMouseDown(e)
End Sub
Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
mouseDownState = False
MyBase.OnMouseUp(e)
End Sub
' Enable the item only if its parent item is in the checked state
' and its Enabled property has not been explicitly set to false.
Public Overrides Property Enabled() As Boolean
Get
Dim ownerMenuItem As ToolStripMenuItem = _
TryCast(OwnerItem, ToolStripMenuItem)
' Use the base value in design mode to prevent the designer
' from setting the base value to the calculated value.
If Not DesignMode AndAlso _
ownerMenuItem IsNot Nothing AndAlso _
ownerMenuItem.CheckOnClick Then
Return MyBase.Enabled AndAlso ownerMenuItem.Checked
Else
Return MyBase.Enabled
End If
End Get
Set(ByVal value As Boolean)
MyBase.Enabled = value
End Set
End Property
' When OwnerItem becomes available, if it is a ToolStripMenuItem
' with a CheckOnClick property value of true, subscribe to its
' CheckedChanged event.
Protected Overrides Sub OnOwnerChanged(ByVal e As EventArgs)
Dim ownerMenuItem As ToolStripMenuItem = _
TryCast(OwnerItem, ToolStripMenuItem)
If ownerMenuItem IsNot Nothing AndAlso _
ownerMenuItem.CheckOnClick Then
AddHandler ownerMenuItem.CheckedChanged, New _
EventHandler(AddressOf OwnerMenuItem_CheckedChanged)
End If
MyBase.OnOwnerChanged(e)
End Sub
' When the checked state of the parent item changes,
' repaint the item so that the new Enabled state is displayed.
Private Sub OwnerMenuItem_CheckedChanged( _
ByVal sender As Object, ByVal e As EventArgs)
Invalidate()
End Sub
End Class
Second Create a Class of Form1
Public Class Form1
Inherits Form
Private sample As New MenuStrip()
Private mainToolStripMenuItem As New ToolStripMenuItem()
Private toolStripMenuItem1 As New ToolStripMenuItem()
Private toolStripRadioButtonMenuItem1 As New ToolStripRadioButtonMenuItem()
Private toolStripRadioButtonMenuItem2 As New ToolStripRadioButtonMenuItem()
Private toolStripRadioButtonMenuItem3 As New ToolStripRadioButtonMenuItem()
Private toolStripRadioButtonMenuItem4 As New ToolStripRadioButtonMenuItem()
Private toolStripRadioButtonMenuItem5 As New ToolStripRadioButtonMenuItem()
Private toolStripRadioButtonMenuItem6 As New ToolStripRadioButtonMenuItem()
Public Sub New()
Me.mainToolStripMenuItem.Text = "main"
toolStripRadioButtonMenuItem1.Text = "option 1"
toolStripRadioButtonMenuItem2.Text = "option 2"
toolStripRadioButtonMenuItem3.Text = "option 2-1"
toolStripRadioButtonMenuItem4.Text = "option 2-2"
toolStripRadioButtonMenuItem5.Text = "option 3-1"
toolStripRadioButtonMenuItem6.Text = "option 3-2"
toolStripMenuItem1.Text = "toggle"
toolStripMenuItem1.CheckOnClick = True
mainToolStripMenuItem.DropDownItems.AddRange(New ToolStripItem() { _
toolStripRadioButtonMenuItem1, toolStripRadioButtonMenuItem2, _
toolStripMenuItem1})
toolStripRadioButtonMenuItem2.DropDownItems.AddRange( _
New ToolStripItem() {toolStripRadioButtonMenuItem3, _
toolStripRadioButtonMenuItem4})
toolStripMenuItem1.DropDownItems.AddRange(New ToolStripItem() { _
toolStripRadioButtonMenuItem5, toolStripRadioButtonMenuItem6})
sample.Items.AddRange(New ToolStripItem() {mainToolStripMenuItem})
Controls.Add(sample)
MainMenuStrip = sample
Text = "ToolStripRadioButtonMenuItem demo"
End Sub
End Class
Last is Create a Class for Program
Public Class Program
<STAThread()> Public Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
Screenshot
.
Credits to Karl Erickson and to his blog about RadioButton and Menustrip.
Check his blog here.

Invoke part of mainform

I have an application with 8 threads. The main of the app is to display realtime information from 4 outputs and also write the information to a file.
Now, I do not know very much in the domain of multi-threading, but I have succeeded in creating the 4 threads,and if I do not log the info into the rich text boxes, they work ok, they write the info into the files.
My question is: Can I display real time info, from each output on the same form (MainForm)
Outputs work independent one to each other
Below is the code I use to log the info into the richtextbox:
Public Sub LogInBoxOutput2(ByVal [RichTextBox] As RichTextBox, textColor As Color, ByVal [text] As String, Optional logToFile As Boolean = False)
Dim textToWrite As String = "[" & Now.ToString("dd:MM:yyyy HH:mm:ss.fff") & "] - " & [text]
If logNodesValues Then
Me.InvokeIfRequired(Sub()
If textColor = Nothing Then
[RichTextBox].SelectionColor = Color.Black
Else
[RichTextBox].SelectionColor = textColor
End If
[RichTextBox].SelectedText = textToWrite
If scrollToBottom Then
[RichTextBox].Select([RichTextBox].Text.Length - 1, 0)
[RichTextBox].ScrollToCaret()
End If
[RichTextBox].AppendText(vbCrLf)
If logToFile Then
writeToFileQueue2.Enqueue(textToWrite & vbCrLf)
End If
End Sub)
Else
writeToFileQueue2.Enqueue(textToWrite & vbCrLf)
End If
End Sub
<Extension()>
Public Sub InvokeIfRequired(ByVal Control As Control, ByVal Method As Action)
If Control.InvokeRequired Then
Control.Invoke(Method)
Else
Method.Invoke()
End If
End Sub
Do you have any ideas, what could I do? Is there something like in ASP.NET where you could refresh only a frame/part of the page (meaning to invoke only a part of the mainform)?
thank you
Instead of invoking you should queue all the messages to be outputted to the UI as well in order to give the UI and your processor some rest. Then use a System.Windows.Forms.Timer with an Interval of 1 to empty that queue as often as possible (approximately every 50 ms) and write the messages into each RichTextBox.
You can define your own data type that holds the necessary information for each message:
Public Structure OutputMessage
Public Color As Color?
Public Text As String
Public [RichTextBox] As RichTextBox
Public ScrollToBottom As Boolean
Public Sub New(ByVal Text As String, ByVal Color As Color?, ByVal ScrollToBottom As Boolean, ByVal [RichTextBox] As RichTextBox)
Me.Text = Text
Me.Color = Color
Me.ScrollToBottom = ScrollToBottom
Me.RichTextBox = [RichTextBox]
End Sub
End Structure
Then in your form:
Private MessageQueue As New ConcurrentQueue(Of OutputMessage)
Dim WithEvents UpdateTimer As New Timer With {.Interval = 1, .Enabled = True}
Private Sub UpdateTimer_Tick(sender As Object, e As EventArgs) Handles UpdateTimer.Tick
Dim Message As OutputMessage
While MessageQueue.TryDequeue(Message)
PrintMessage(Message)
End While
End Sub
Private Sub PrintMessage(ByVal Message As OutputMessage)
If Not Message.Color.HasValue Then
Message.RichTextBox.SelectionColor = Color.Black
Else
Message.RichTextBox.SelectionColor = Message.Color.Value
End If
Message.RichTextBox.SelectedText = Message.Text
If Message.ScrollToBottom Then
Message.RichTextBox.Select(Message.RichTextBox.Text.Length - 1, 0)
Message.RichTextBox.ScrollToCaret()
End If
Message.RichTextBox.AppendText(vbCrLf)
End Sub
Finally, in your threads:
Public Sub LogInBoxOutput2(ByVal [RichTextBox] As RichTextBox, textColor As Color?, ByVal text As String, Optional logToFile As Boolean = False)
Dim textToWrite As String = "[" & Now.ToString("dd:MM:yyyy HH:mm:ss.fff") & "] - " & text
If logNodeValues Then
MessageQueue.Enqueue(New OutputMessage(textToWrite, textColor, scrollToBottom, [RichTextBox]))
End If
If logToFile Then
writeToFileQueue2.Enqueue(textToWrite & vbCrLf)
End If
End Sub

Parse Control name to Variable name

I have a var called as "Cheat_Enabled":
Dim Cheat_Enabled As Boolean
And a Checkbox called as "CheckBox_Cheat" with the tag "Cheat"
Now I want to do a dynamic method to change the value of the var by spliting (or something) the name of the control.
For example, something like this (the code obviouslly don't work):
Private Sub CheckBoxes_CheckedChanged(sender As Object, e As EventArgs) Handles _
CheckBox_Cheat.CheckedChanged
Dim SenderVarEquivalent As Object = _
Me.variables.Find(sender.Tag & "_Enabled")(0)
If sender.Checked Then SenderVarEquivalent = True _
Else SenderVarEquivalent = False
End Sub
' Info:
' Sender.Tag = "Cheat"
' Sender.Name = "CheckBox_Cheat"
' VariableName = "Cheat_Enabled"
I think this can be done with one CType or DirectCast or GetObject but I don't know exactly how to do it.
UPDATE:
This is a similar easy code but instead of converting ControlName to VariableName it is converting the control tag to the ControlName Object of the Checkbox:
Public Class Form1
Dim Cheat_Enabled As Boolean = True
Private Sub CheckBox_Cheat_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_Cheat.CheckedChanged
CType(Controls("CheckBox" & "_" & sender.tag), CheckBox).Checked = Cheat_Enabled
End Sub
End Class
I hope if I can do the same to CType the control name to catch the variablename and use it, for example like this:
Dim Cheat_Enabled As Boolean
Private Sub CheckBox_Cheat_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_Cheat.CheckedChanged
' Sender.name is : "CheckBox_Cheat"
' Sender.tag is : "Cheat"
' Variable name is: "Cheat_Enabled"
If sender.checked Then
CType(Variable(sender.tag & "_Enabled"), Boolean) = True
Else
CType(Variable(sender.tag & "_Enabled"), Boolean) = False
End If
End Sub
In MSDN you can find a VB.Net example how to enumerate all members of a given class:
Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic
Class MyFindMembersClass
Public Shared Sub Main()
Dim objTest As New Object()
Dim objType As Type = objTest.GetType()
Dim arrayMemberInfo() As MemberInfo
Try
'Find all static or public methods in the Object
'class that match the specified name.
arrayMemberInfo = objType.FindMembers(MemberTypes.Method, _
BindingFlags.Public Or BindingFlags.Static _
Or BindingFlags.Instance, _
New MemberFilter(AddressOf DelegateToSearchCriteria), _
"ReferenceEquals")
Dim index As Integer
For index = 0 To arrayMemberInfo.Length - 1
Console.WriteLine("Result of FindMembers -" + ControlChars.Tab + _
arrayMemberInfo(index).ToString() + ControlChars.Cr)
Next index
Catch e As Exception
Console.WriteLine("Exception : " + e.ToString())
End Try
End Sub 'Main
Public Shared Function DelegateToSearchCriteria _
(ByVal objMemberInfo As MemberInfo, _
ByVal objSearch As Object) As Boolean
' Compare the name of the member function with the filter criteria.
If objMemberInfo.Name.ToString() = objSearch.ToString() Then
Return True
Else
Return False
End If
End Function 'DelegateToSearchCriteria
End Class 'MyFindMembersClass
Another alternative would be to put all your boolean variables into one Dictionary object. This would allow you to access the boolean values "by name" without using Reflection.
Example for illustration:
Imports System.Collections.Generic
Module vbModule
Class Example
Private _dictionary
Public Sub New()
' Allocate and populate the field Dictionary.
Me._dictionary = New Dictionary(Of String, Boolean)
Me._dictionary.Add("v1", False)
Me._dictionary.Add("v2", True)
End Sub
Public Function GetValue(name as String) As Boolean
' Return value from private Dictionary.
Return Me._dictionary.Item(name)
End Function
Public Sub SetValue(name as String, val as Boolean)
Me._dictionary.Item(name) = val
End Sub
End Class
Sub Main()
' Allocate an instance of the class.
Dim example As New Example
' Write a value from the class.
Console.WriteLine(example.GetValue("v1"))
Console.WriteLine(example.GetValue("v2"))
example.SetValue("v1", true)
Console.WriteLine(example.GetValue("v1"))
End Sub
End Module

Vb.net app to track webbrowser popup

I have a webbrowser control on my form, when I navigate to a certain page it opens a popup which opens the page in the current default browser for windows, in this case IE. I would like to access the source code for this page. I dont want to close it, I just want to grab the html.
Thanks for your help.
Edit:
Slution:
eWebbrowser.vb :
Imports System
Imports System.Text
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Security.Permissions
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class eWebbrowser
Inherits System.Windows.Forms.WebBrowser
#Region " COM Imports Etc..."
<StructLayout(LayoutKind.Sequential)> _
Public Structure OLECMDTEXT
Public cmdtextf As UInt32
Public cwActual As UInt32
Public cwBuf As UInt32
Public rgwz As Char
End Structure
<StructLayout(LayoutKind.Sequential)> _
Public Structure OLECMD
Public cmdID As Long
Public cmdf As UInt64
End Structure
' Interop - IOleCommandTarget (See MSDN - http://support.microsoft.com/?kbid=311288)
<ComImport(), Guid("b722bccb-4e68-101b-a2bc-00aa00404770"), _
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface IOleCommandTarget
Sub QueryStatus(ByRef pguidCmdGroup As Guid, ByVal cCmds As UInt32, _
<MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=1)> ByVal prgCmds As OLECMD, _
ByRef pCmdText As OLECMDTEXT)
Sub Exec(ByRef pguidCmdGroup As Guid, ByVal nCmdId As Long, _
ByVal nCmdExecOpt As Long, ByRef pvaIn As Object, _
ByRef pvaOut As Object)
End Interface
Private cmdGUID As New Guid(&HED016940, -17061, _
&H11CF, &HBA, &H4E, &H0, &HC0, &H4F, &HD7, &H8, &H16)
#Region " Commands Enumeration "
'There are a ton of ole commands, we are only using a couple, msdn research will
'allow you to figure out which ones you want to use.
Enum oCommands As Long
Options
Find = 1
ViewSource = 2
'////////////////////////////////////////
ID_FILE_SAVEAS = 32771
ID_FILE_PAGESETUP = 32772
ID_FILE_IMPORTEXPORT = 32774
ID_FILE_PRINTPREVIEW = 32776
ID_FILE_NEWIE = 32779
ID_FILE_NEWMAIL = 32780
PID_FILE_NEWINTERNETCALL = 32781
ID_FILE_ADDTRUST = 32782
ID_FILE_ADDLOCAL = 32783
DLCTL_BGSOUNDS = &H40
DLCTL_DLIMAGES = &H10
DLCTL_DOWNLOADONLY = &H800
DLCTL_FORCEOFFLINE = &H10000000
DLCTL_NO_BEHAVIORS = &H800
DLCTL_NO_CLIENTPULL = &H20000000
DLCTL_NO_DLACTIVEXCTLS = &H400
DLCTL_NO_FRAMEDOWNLOAD = &H1000
DLCTL_NO_JAVA = &H100
DLCTL_NO_METACHARSET = &H10000
DLCTL_NO_RUNACTIVEXCTLS = &H200
DLCTL_NO_SCRIPTS = &H80
'DLCTL_OFFLINE DLCTL_OFFLINEIFNOTCONNECTED
DLCTL_OFFLINEIFNOTCONNECTED = &H80000000
DLCTL_PRAGMA_NO_CACHE = &H4000
DLCTL_RESYNCHRONIZE = &H2000
DLCTL_SILENT = &H40000000
DLCTL_URL_ENCODING_DISABLE_UTF8 = &H20000
DLCTL_URL_ENCODING_ENABLE_UTF8 = &H40000
DLCTL_VIDEOS = &H20
End Enum
#End Region
#End Region
'Just a little easier way to get at it.
Public ReadOnly Property CurrentURL() As String
Get
Return Me.Document.Url.ToString
End Get
End Property
Public Sub New()
MyBase.New()
End Sub
#Region " Dialogs "
Public Sub ShowOpen()
Dim cdlOpen As New OpenFileDialog
Try
cdlOpen.Filter = "HTML Files (*.htm)|*.htm|HTML Files (*.html)|*.html|TextFiles" & _
"(*.txt)|*.txt|Gif Files (*.gif)|*.gif|JPEG Files (*.jpg)|*.jpeg|" & _
"PNG Files (*.png)|*.png|Art Files (*.art)|*.art|AU Fles (*.au)|*.au|" & _
"AIFF Files (*.aif|*.aiff|XBM Files (*.xbm)|*.xbm|All Files (*.*)|*.*"
cdlOpen.Title = " Open File "
cdlOpen.ShowDialog()
If cdlOpen.FileName > Nothing Then
Me.Navigate(cdlOpen.FileName)
End If
Catch ex As Exception
Throw New Exception(ex.Message.ToString)
End Try
End Sub
Public Sub ShowSource()
Dim cmdt As IOleCommandTarget
Dim o As Object = Nothing
Dim oIE As Object = Nothing
Try
cmdt = CType(Me.Document.DomDocument, IOleCommandTarget)
cmdt.Exec(cmdGUID, oCommands.ViewSource, 1, o, o)
Catch ex As Exception
Throw New Exception(ex.Message.ToString, ex.InnerException)
Finally
cmdt = Nothing
End Try
End Sub
Public Sub ShowFindDialog()
Dim cmdt As IOleCommandTarget
Dim o As Object = Nothing
Dim oIE As Object = Nothing
Try
cmdt = CType(Me.Document.DomDocument, IOleCommandTarget)
cmdt.Exec(cmdGUID, oCommands.Find, 0, o, o)
Catch ex As Exception
Throw New Exception(ex.Message.ToString, ex.InnerException)
Finally
cmdt = Nothing
End Try
End Sub
Public Sub AddToFavorites(Optional ByVal strURL As String = "", Optional ByVal strTitle As String = "")
Dim oHelper As Object = Nothing
Try
oHelper = New ShellUIHelper
oHelper.AddFavorite(Me.Document.Url.ToString, Me.DocumentTitle.ToString)
Catch ex As Exception
Throw New Exception(ex.Message.ToString)
End Try
If oHelper IsNot Nothing AndAlso Marshal.IsComObject(oHelper) Then
Marshal.ReleaseComObject(oHelper)
End If
End Sub
Public Sub ShowOrganizeFavorites()
'Organize Favorites
Dim helper As Object = Nothing
Try
helper = New ShellUIHelper()
helper.ShowBrowserUI("OrganizeFavorites", 0)
Finally
If helper IsNot Nothing AndAlso Marshal.IsComObject(helper) Then
Marshal.ReleaseComObject(helper)
End If
End Try
End Sub
Public Sub SendToDesktop()
'Shortcut to desktop
Dim helper As Object = Nothing
Try
helper = New ShellUIHelper()
helper.AddDesktopComponent(Me.Document.Url.ToString, "website")
Finally
If helper IsNot Nothing AndAlso Marshal.IsComObject(helper) Then
Marshal.ReleaseComObject(helper)
End If
End Try
End Sub
''' <summary>
''' This Will launch the internet option dialog.
''' </summary>
''' <remarks></remarks>
Public Sub ShowInternetOptions()
Shell("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,0", vbNormalFocus)
End Sub
Public Sub ShowPrivacyReport()
Shell("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,2", vbNormalFocus)
End Sub
#End Region
#Region " Extended "
<ComImport(), _
Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"), _
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), _
TypeLibType(TypeLibTypeFlags.FHidden)> _
Public Interface DWebBrowserEvents2
<DispId(250)> _
Sub BeforeNavigate2(<[In](), MarshalAs(UnmanagedType.IDispatch)> ByVal pDisp As Object, _
<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByRef URL As String, _
<InAttribute()> ByRef flags As Object, _
<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByRef targetFrameName As String, _
<InAttribute()> ByRef postdata As Object, _
<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByRef headers As String, _
<InAttribute(), OutAttribute()> ByRef cancel As Boolean)
'Note: Postdata is a SafeArray but for some reason, if I do a proper declaration, the event will not be raised:
'<[In](), MarshalAs(UnmanagedType.SafeArray, safearraysubtype:=VarEnum.VT_UI1)> ByRef postdata() As Byte, _
<DispId(273)> _
Sub NewWindow3(<InAttribute(), MarshalAs(UnmanagedType.IDispatch)> ByVal pDisp As Object, _
<InAttribute(), OutAttribute()> ByRef cancel As Boolean, _
<InAttribute()> ByRef Flags As Object, _
<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByRef UrlContext As String, _
<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByRef Url As String)
End Interface
Public Enum NWMF
NWMF_UNLOADING = &H1&
NWMF_USERINITED = &H2&
NWMF_FIRST_USERINITED = &H4&
NWMF_OVERRIDEKEY = &H8&
NWMF_SHOWHELP = &H10&
NWMF_HTMLDIALOG = &H20&
NWMF_FROMPROXY = &H40&
End Enum
Private cookie As AxHost.ConnectionPointCookie
Private wevents As WebBrowserExtendedEvents
'This method will be called to give you a chance to create your own event sink
Protected Overrides Sub CreateSink()
'MAKE SURE TO CALL THE BASE or the normal events won't fire
MyBase.CreateSink()
wevents = New WebBrowserExtendedEvents(Me)
cookie = New AxHost.ConnectionPointCookie(Me.ActiveXInstance, wevents, GetType(DWebBrowserEvents2))
End Sub
Protected Overrides Sub DetachSink()
If Not cookie Is Nothing Then
cookie.Disconnect()
cookie = Nothing
End If
MyBase.DetachSink()
End Sub
'This new event will fire when the page is navigating
Public Delegate Sub WebBrowserNavigatingExtendedEventHandler(ByVal sender As Object, ByVal e As WebBrowserNavigatingExtendedEventArgs)
Public Event NavigatingExtended As WebBrowserNavigatingExtendedEventHandler
'This event will fire when a new window is about to be opened
Public Delegate Sub WebBrowserNewWindowExtendedEventHandler(ByVal sender As Object, ByVal e As WebBrowserNewWindowExtendedEventArgs)
Public Event NewWindowExtended As WebBrowserNewWindowExtendedEventHandler
Protected Friend Sub OnNavigatingExtended(ByVal Url As String, ByVal Frame As String, ByVal Postdata As Byte(), ByVal Headers As String, ByRef Cancel As Boolean)
Dim e As WebBrowserNavigatingExtendedEventArgs = New WebBrowserNavigatingExtendedEventArgs(Url, Frame, Postdata, Headers)
RaiseEvent NavigatingExtended(Me, e)
Cancel = e.Cancel
End Sub
Protected Friend Sub OnNewWindowExtended(ByVal Url As String, ByRef Cancel As Boolean, ByVal Flags As NWMF, ByVal UrlContext As String)
Dim e As WebBrowserNewWindowExtendedEventArgs = New WebBrowserNewWindowExtendedEventArgs(Url, UrlContext, Flags)
RaiseEvent NewWindowExtended(Me, e)
Cancel = e.Cancel
End Sub
Public Overloads Sub Navigate2(ByVal URL As String)
MyBase.Navigate(URL)
End Sub
#End Region
#Region " Extended Event Classes "
'This class will capture events from the WebBrowser
Friend Class WebBrowserExtendedEvents
Inherits System.Runtime.InteropServices.StandardOleMarshalObject
Implements DWebBrowserEvents2
Private m_Browser As eWebbrowser
Public Sub New(ByVal browser As eWebbrowser)
m_Browser = browser
End Sub
'Implement whichever events you wish
Public Sub BeforeNavigate2(ByVal pDisp As Object, ByRef URL As String, ByRef flags As Object, ByRef targetFrameName As String, ByRef postData As Object, ByRef headers As String, ByRef cancel As Boolean) Implements DWebBrowserEvents2.BeforeNavigate2
m_Browser.OnNavigatingExtended(URL, targetFrameName, CType(postData, Byte()), headers, cancel)
End Sub
Public Sub NewWindow3(ByVal pDisp As Object, ByRef Cancel As Boolean, ByRef Flags As Object, ByRef UrlContext As String, ByRef Url As String) Implements DWebBrowserEvents2.NewWindow3
m_Browser.OnNewWindowExtended(Url, Cancel, CType(Flags, NWMF), UrlContext)
End Sub
End Class
Public Class WebBrowserNewWindowExtendedEventArgs
Inherits CancelEventArgs
Private m_Url As String
Private m_UrlContext As String
Private m_Flags As NWMF
Public ReadOnly Property Url() As String
Get
Return m_Url
End Get
End Property
Public ReadOnly Property UrlContext() As String
Get
Return m_UrlContext
End Get
End Property
Public ReadOnly Property Flags() As NWMF
Get
Return m_Flags
End Get
End Property
Public Sub New(ByVal url As String, ByVal urlcontext As String, ByVal flags As NWMF)
m_Url = url
m_UrlContext = urlcontext
m_Flags = flags
End Sub
End Class
'First define a new EventArgs class to contain the newly exposed data
Public Class WebBrowserNavigatingExtendedEventArgs
Inherits CancelEventArgs
Private m_Url As String
Private m_Frame As String
Private m_Postdata() As Byte
Private m_Headers As String
Public ReadOnly Property Url() As String
Get
Return m_Url
End Get
End Property
Public ReadOnly Property Frame() As String
Get
Return m_Frame
End Get
End Property
Public ReadOnly Property Headers() As String
Get
Return m_Headers
End Get
End Property
Public ReadOnly Property Postdata() As String
Get
Return PostdataToString(m_Postdata)
End Get
End Property
Public ReadOnly Property PostdataByte() As Byte()
Get
Return m_Postdata
End Get
End Property
Public Sub New(ByVal url As String, ByVal frame As String, ByVal postdata As Byte(), ByVal headers As String)
m_Url = url
m_Frame = frame
m_Postdata = postdata
m_Headers = headers
End Sub
Private Function PostdataToString(ByVal p() As Byte) As String
'not sexy but it works...
Dim tabpd() As Byte, bstop As Boolean = False, stmp As String = "", i As Integer = 0
tabpd = p
If tabpd Is Nothing OrElse tabpd.Length = 0 Then
Return ""
Else
For i = 0 To tabpd.Length - 1
stmp += ChrW(tabpd(i))
Next
stmp = Replace(stmp, ChrW(13), "")
stmp = Replace(stmp, ChrW(10), "")
stmp = Replace(stmp, ChrW(0), "")
End If
If stmp = Nothing Then
Return ""
Else
Return stmp
End If
End Function
End Class
#End Region
<ComImport(), Guid("64AB4BB7-111E-11D1-8F79-00C04FC2FBE1")> _
Public Class ShellUIHelper
'
End Class
End Class
form load:
Public WithEvents wb As eWebbrowser
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim brws As New eWebbrowser
wb = brws
End Sub
Events:
Private Sub wb_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles wb.NewWindow
e.Cancel = True
End Sub
The New Event:
Private Sub wb_NewWindowExtended(ByVal sender As Object, ByVal e As eWebbrowser.WebBrowserNewWindowExtendedEventArgs) Handles wb.NewWindowExtended
e.Cancel = True
Dim url As String = e.Url
msgbox(url) //This Is The Url!!
End Sub

How to change the Caption of the Command on the toolbar from a Macro in VS2010?

From a macro I am accessing a command that is on the toolbar:
Dim name As String = "Macros.MyMacros.MyMacros.ToggleExceptions"
Dim cmd As EnvDTE.Command = DTE.Commands.Item(name)
How do I now change the caption of the command on the toolbar? It does not seem to have the necessary properties. Do I need to cast it to something else?
I've implemented it:
Private Sub Main()
Const BAR_NAME As String = "MenuBar"
Const CTL_NAME = "Foo"
ChangeCommandCaption(BAR_NAME, CTL_NAME, "Bar")
End Sub
Private Sub ChangeCommandCaption(ByVal cmdBarName As String, ByVal ctlName As String, ByVal caption As String)
Dim bars As Microsoft.VisualStudio.CommandBars.CommandBars
bars = DirectCast(DTE.CommandBars, Microsoft.VisualStudio.CommandBars.CommandBars)
If bars Is DBNull.Value Then Exit Sub
Dim menuBar As CommandBar = bars.Item(cmdBarName)
If menuBar Is DBNull.Value Then Exit Sub
Dim cmdBarCtl As CommandBarControl
Try
cmdBarCtl = menuBar.Controls.Item(ctlName)
If cmdBarCtl Is DBNull.Value Then Exit Sub
Catch ex As Exception
Exit Sub
End Try
cmdBarCtl.Caption = caption
End Sub