Vb.net app to track webbrowser popup - vb.net

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

Related

CoreAudio in vb.net 6.0 Windows 11 : Is there a way to do a ControlChangeNotify callback?

I am writing a volume control app in vb.net 6.0, using a reference to CoreAudioApi.dll.
I can:
Change the volume of the default render and capture devices.
Mute the default devices.
Alter the balance on the render device
List the full names, guid string and status of all the devices
However, despite a lot of research, I can not setup a callback for ControlChangeNotify.
It appears to be simple in C, however I am writing in VB. Can any one suggest a solution?
Update 18/12/2022 #Jimi supplied some very useful definitions and I have edited the post to show the current code attempts. I can get the master default volume using masterVol = GetMasterVolumeObject() as an IAudioEndpointVolume.
Update 22/12/2022 Following a re-read of many postings it became apparent that it was important to create a persistent reference to mastervol and the class reference (MyCallBack) to the class module implementing IAudioEndpointVolumeCallback.
Update 24/12/2022 The AudioCallback class is now firing when volume/mute are changed internally and externally. Transferring the callback data to the main form is problematic. I now have a working system which involves:
Declaring public events in the call back class for each type of control I want to change in the main form.
Initiating a BackgroundWorker to Process the data 10mS after being called by the callback class.
Calculating new audio values from the pNotifyData pointer.
RaiseEvent for each slider/checkbox and label in the main form that needs updating.
AddHandler in the main form to process the callback events.
Create handler routines with delegates for each control type.
From my point of view this topic is solved.
My thanks to #Jimi for his contribution.
Latest Updates:
Option Explicit On
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class AudioCallback
Implements IAudioEndpointVolumeCallback
Public Event LabelReady(sender As AudioCallback, ByVal T As String)
Public Event SliderReady(sender As AudioCallback, EP As String, ByVal T As Integer)
Public Event CheckReady(sender As AudioCallback, EP As String, ByVal T As Boolean)
Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
' Move to global structure
Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))
BackGround() ' Asynchronous call and delagate controls
Return 0
End Function
Private Sub BackGround()
Dim bgw = New BackgroundWorker()
AddHandler bgw.DoWork,
Sub()
System.Threading.Thread.Sleep(10)
End Sub
AddHandler bgw.RunWorkerCompleted,
Sub()
Update()
End Sub
bgw.RunWorkerAsync()
End Sub
Private Sub Update()
Dim svolL As Integer
Dim svolR As Integer
Dim balance As Integer
'ChkMaster.Checked = Gstructure.bMuted
RaiseEvent CheckReady(Me, "R", Gstructure.bMuted)
svolL = 0.5 + 100 * Gstructure.Left
svolR = 0.5 + 100 * Gstructure.Right
If svolL = svolR Then
balance = 0
Else
If svolR > svolL Then
balance = 100 - svolL * 100.0 / svolR
Else
balance = -(100 - svolR * 100.0 / svolL)
End If
End If
RaiseEvent SliderReady(Me, "RV", 0.5 + 100 * Gstructure.fMasterVolume) ' HMaster.Value = 0.5 + 100 * Gstructure.fMasterVolume
RaiseEvent SliderReady(Me, "RB", balance) ' HBalance.Value = balance
'LGuid.Text = Gstructure.guidEventContext.ToString
RaiseEvent LabelReady(Me, Gstructure.guidEventContext.ToString)
End Sub
End Class
' Main form Extracts ============================================
Imports CoreAudioApi
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
' events for handling AudioCallback events
AddHandler MyCallBack.LabelReady, AddressOf LReady
AddHandler MyCallBack.SliderReady, AddressOf HReady
AddHandler MyCallBack.CheckReady, AddressOf CReady
End Sub
' Label Guid displays Callback GUID
' CheckBox ChkMaster displays Mute status
' Horizontal scrollbar HMaster displays default render volume
' Horizontal scrollbar HBalance displays default render balance
' The global variable IsSettingMaster prevents code associated
' with altering the value of the sliders from re-setting
' the volume / balance.
Private Sub LReady(sender As AudioCallback, Data As String) ' Set GUID label for Render
UpdateLabel(LGuid, Data)
End Sub
Private Delegate Sub UpdateLabelDelegate(TB As Label, param As String)
Private Sub UpdateLabel(TB As Label, param As String)
If TB.InvokeRequired Then
TB.Invoke(New UpdateLabelDelegate(AddressOf UpdateLabel), New Object() {TB, param})
Else
TB.Text = param
End If
End Sub
Private Sub CReady(sender As AudioCallback, EP As String, Data As Boolean) ' Set Master (Render) Mute checkbox
If EP = "R" Then UpdateChkbox(ChkMaster, Data)
End Sub
Private Delegate Sub UpdateChkboxDelegate(TB As CheckBox, param As Boolean)
Private Sub UpdateChkbox(TB As CheckBox, param As Boolean)
If TB.InvokeRequired Then
TB.Invoke(New UpdateChkboxDelegate(AddressOf UpdateChkbox), New Object() {TB, param})
Else
TB.Checked = param
End If
End Sub
Private Sub HReady(sender As AudioCallback, EP As String, Data As Integer) ' Set Master (Render) Volume / Master Balance slide
IsSettingMaster = True
If EP = "RV" Then UpdateHslide(HMaster, Data)
If EP = "RB" Then UpdateHslide(HBalance, Data)
IsSettingMaster = False
End Sub
Private Delegate Sub UpdateHslideDelegate(TB As HScrollBar, param As Integer)
Private Sub UpdateHslide(TB As HScrollBar, param As Integer)
If TB.InvokeRequired Then
TB.Invoke(New UpdateHslideDelegate(AddressOf UpdateHslide), New Object() {TB, param})
Else
TB.Value = param
End If
End Sub
History:
' ===============================
' Public Class containing Callback:
Option Explicit On
Imports System.Runtime.InteropServices
Public Class AudioCallback
Implements IAudioEndpointVolumeCallback
Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
' Move to global structure
Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))
' Need mechanism to process new data in main form
' Must be asynchronous
' Raise event did not work
' Enabling Timer did not work
HaveChange = True ' Flag global variable
Return 0
End Function
End Class
' ===============================
' Public Class to Setup Callback:
Option Explicit On
Imports System.Runtime.InteropServices
' Implements IMMDevice, IMMDeviceEnumerator, IAudioEndpointVolume
' developed from https://exchangetuts.com/how-to-check-if-the-system-audio-is-muted-1641156904496320
Public Class CoreAudio
' Public definition in ModCoreaudioAlt https://stackoverflow.com/questions/52001368/how-to-check-if-the-system-audio-is-muted/52013031#52013031
' Public Interface IAudioEndpointVolumeCallback
' Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
' Public Interface IMMDevice
' Public Interface IMMDeviceEnumerator
' End Public definition in ModCoreaudioAlt ==============================
Dim CLSID_MMDeviceEnumerator As Guid = New Guid("{BCDE0395-E52F-467C-8E3D-C4579291692E}")
Dim MMDeviceEnumeratorType As Type = Type.GetTypeFromCLSID(CLSID_MMDeviceEnumerator, True)
Private hr As Integer
Friend Enum EDataFlow
eRender
eCapture
eAll
EDataFlow_enum_count
End Enum
Friend Enum ERole
eConsole
eMultimedia
eCommunications
ERole_enum_count
End Enum
<Flags>
Friend Enum CLSCTX As UInteger
CLSCTX_INPROC_SERVER = &H1 ' In CLSCTX_ALL
CLSCTX_INPROC_HANDLER = &H2 ' In CLSCTX_ALL
CLSCTX_LOCAL_SERVER = &H4 ' In CLSCTX_ALL
CLSCTX_INPROC_SERVER16 = &H8
CLSCTX_REMOTE_SERVER = &H10 ' In CLSCTX_ALL
CLSCTX_INPROC_HANDLER16 = &H20
CLSCTX_RESERVED1 = &H40
CLSCTX_RESERVED2 = &H80
CLSCTX_RESERVED3 = &H100
CLSCTX_RESERVED4 = &H200
CLSCTX_NO_CODE_DOWNLOAD = &H400
CLSCTX_RESERVED5 = &H800
CLSCTX_NO_CUSTOM_MARSHAL = &H1000
CLSCTX_ENABLE_CODE_DOWNLOAD = &H2000
CLSCTX_NO_FAILURE_LOG = &H4000
CLSCTX_DISABLE_AAA = &H8000
CLSCTX_ENABLE_AAA = &H10000
CLSCTX_FROM_DEFAULT_CONTEXT = &H20000
CLSCTX_ACTIVATE_32_BIT_SERVER = &H40000
CLSCTX_ACTIVATE_64_BIT_SERVER = &H80000
CLSCTX_INPROC = CLSCTX_INPROC_SERVER Or CLSCTX_INPROC_HANDLER
CLSCTX_SERVER = CLSCTX_INPROC_SERVER Or CLSCTX_LOCAL_SERVER Or CLSCTX_REMOTE_SERVER ' In CLSCTX_ALL
CLSCTX_ALL = CLSCTX_SERVER Or CLSCTX_INPROC_HANDLER
End Enum
Friend Function GetMasterVolumeObject() As IAudioEndpointVolume
' Get the default IAudioEndpintVolume as "ppEndpoint" for eRender & eMultimedia
Dim deviceEnumerator As IMMDeviceEnumerator = Nothing
Dim MediaDevice As IMMDevice = Nothing
Dim ppEndpoint As IAudioEndpointVolume = Nothing
Dim EndPointVolID As Guid = GetType(IAudioEndpointVolume).GUID
Try
Dim MMDeviceEnumerator As Object = Activator.CreateInstance(MMDeviceEnumeratorType)
deviceEnumerator = CType(MMDeviceEnumerator, IMMDeviceEnumerator)
deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, MediaDevice)
MediaDevice.Activate(EndPointVolID, CLSCTX.CLSCTX_ALL, IntPtr.Zero, ppEndpoint)
Catch ex As Exception
Form1.Showme("Error in GetMasterVolumeObject: " & ex.Message, Color.Red)
ppEndpoint = Nothing
Finally
If Not IsNothing(deviceEnumerator) Then Marshal.ReleaseComObject(deviceEnumerator)
If Not IsNothing(MediaDevice) Then Marshal.ReleaseComObject(MediaDevice)
End Try
Return ppEndpoint
End Function
Public Sub Callback()
Try
masterVol = GetMasterVolumeObject()
' MyCallBack defined in Module ModCoreAudioAlt : Public MyCallBack As New AudioCallback
If IsNothing(MyCallBack) Then
Form1.Showme("Failed to set MyCallBack", Color.Red)
Else
hr = masterVol.RegisterControlChangeNotify(MyCallBack)
If hr <> 0 Then
Form1.Showme("Callback register failed", Color.Red)
If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
Else
Form1.Showme("Callback register OK", Color.Blue)
CallBackOn = True
End If
End If
Catch ex As Exception
Form1.Showme("CallBack error " & ex.Message, Color.Red)
If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
End Try
End Sub
Public Sub Cancelcallback()
If CallBackOn = False Then Exit Sub
hr = masterVol.UnregisterControlChangeNotify(MyCallBack)
If hr <> 0 Then
MsgBox("Callback Failed to UnRegister", vbOK, "Core Audio Callback")
Else
If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
Form1.Showme("Callback Un-register OK", Color.Blue)
CallBackOn = False
End If
End Sub
End Class
' ==============
' Public Module:
Imports System.Runtime.InteropServices
Imports CoreAudioApi
Module ModCoreAudioAlt
' https://stackoverflow.com/questions/74833398/coreaudio-in-vb-net-6-0-windows-11-Is-there-a-way-to-do-a-controlchangenotify
Public CallBackOn As Boolean = False ' Callback is on Flag
Public masterVol As IAudioEndpointVolume = Nothing
Public MyCallBack As New AudioCallback
Public Gstructure As New AUDIO_VOLUME_NOTIFICATION_DATA ' Callback data
Public HaveChange As Boolean = False ' Callback has fired
<ComImport>
<Guid("657804FA-D6AD-4496-8A60-352752AF4F89")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IAudioEndpointVolumeCallback
<PreserveSig()>
Function OnNotify(pNotifyData As IntPtr) As Integer
End Interface
<StructLayout(LayoutKind.Sequential)>
Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
Public guidEventContext As Guid
Public bMuted As Boolean
Public fMasterVolume As Single
Public nChannels As UInteger
Public Left As Single ' .net will not allow pre-dimensioned array (aVolumes(1) as single)
Public Right As Single
End Structure
' https://gist.github.com/sverrirs/d099b34b7f72bb4fb386
<ComImport>
<Guid("5CDF2C82-841E-4546-9722-0CF74078229A")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IAudioEndpointVolume
Function RegisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer
Function UnregisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer
Function GetChannelCount(ByRef channelCount As Integer) As HRESULT
Function SetMasterVolumeLevel() As HRESULT
Function SetMasterVolumeLevelScalar(level As Single, eventContext As Guid) As HRESULT
Function GetMasterVolumeLevel(<Out> ByRef level As Single) As HRESULT
Function GetMasterVolumeLevelScalar(<Out> ByRef level As Single) As HRESULT
Function SetChannelVolumeLevel(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
Function SetChannelVolumeLevelScalar(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
Function GetChannelVolumeLevel(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
Function GetChannelVolumeLevelScalar(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
Function SetMute(<MarshalAs(UnmanagedType.Bool)> isMuted As Boolean, eventContext As Guid) As HRESULT
Function GetMute(<Out> ByRef isMuted As Boolean) As HRESULT
Function GetVolumeStepInfo(<Out> ByRef pnStep As Integer, ByRef pnStepCount As Integer) As HRESULT
Function VolumeStepUp(eventContext As Guid) As HRESULT
Function VolumeStepDown(eventContext As Guid) As HRESULT
Function QueryHardwareSupport(<Out> ByRef hardwareSupportMask As Integer) As HRESULT
Function GetVolumeRange(<Out> ByRef volumeMin As Single, <Out> ByRef volumeMax As Single, <Out> ByRef volumeStep As Single) As HRESULT
End Interface
<ComImport>
<Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IMMDeviceEnumerator
Function EnumAudioEndpoints(ByVal dataFlow As EDataFlow, ByVal dwStateMask As Integer, <Out> ByRef ppDevices As IMMDeviceCollection) As HRESULT
' for 0x80070490 : Element not found
<PreserveSig>
Function GetDefaultAudioEndpoint(ByVal dataFlow As EDataFlow, ByVal role As ERole, <Out> ByRef ppEndpoint As IMMDevice) As HRESULT
Function GetDevice(ByVal pwstrId As String, <Out> ByRef ppDevice As IMMDevice) As HRESULT
Function NotImpl1() As Integer
End Interface
<ComImport>
<Guid("D666063F-1587-4E43-81F1-B948E807363F")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IMMDevice
Function Activate(ByRef iid As Guid, ByVal dwClsCtx As CLSCTX, ByVal pActivationParams As IntPtr, <Out> ByRef ppInterface As IAudioEndpointVolume) As HRESULT
Function OpenPropertyStore(ByVal stgmAccess As Integer, <Out> ByRef ppProperties As IPropertyStore) As HRESULT
Function GetId(<Out> ByRef ppstrId As IntPtr) As HRESULT
Function GetState(<Out> ByRef pdwState As Integer) As HRESULT
End Interface
End Module
' ==========
' Main Form:
Public Class Form1
' Contains:
' HMaster horizonal scroll 0-105 for Volume
' HBalance horizontal scroll -100 to 105 for Balance
' ChkMaster CheckBox for Mute
' LGuid label for Callback GUID
' Uses timer1 with 1 second interval to poll for Callback flag
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If HaveChange = False Then Exit Sub
HaveChange = False
ChkMaster.Checked = Gstructure.bMuted
Dim svolL As Integer = 100 * Gstructure.Left
Dim svolR As Integer = 100 * Gstructure.Right
Dim balance As Integer
If svolL = svolR Then
balance = 0
Else
If svolR > svolL Then
balance = 100 - svolL * 100.0 / svolR
Else
balance = -(100 - svolR * 100.0 / svolL)
End If
End If
HMaster.Value = 100 * Gstructure.fMasterVolume
HBalance.Value = balance
LGuid.Text = (Gstructure.guidEventContext.ToString)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If CallBackOn Then ClassCoreAudio.Cancelcallback()
End Sub
end class

How can I print from an object?

I am having a problem getting my program to print an array. I have created a class with code and I want to be able to use the class to print the array. I have submitted my code below. hopefully Y'all can help me out thanks.
Option Strict On
Imports System.IO
Imports FinalLIB
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fsrFile As StreamReader = New StreamReader("Cars.csv")
Dim line, splitLine(1) As String
Dim bestCars(14) As Cars
Dim counter As Integer
Do Until fsrFile.EndOfStream
line = fsrFile.ReadLine
splitLine = Split(line, ",")
bestCars(counter) = New Cars(splitLine(0), (splitLine(1)), (splitLine(2)), (splitLine(3)))
counter += 1
Loop
Dim strCarMake, strCarModel, intyear, strColorc As Cars
Console.WriteLine(bestCars(3))
End Sub
This is the code from my library created.
Option Strict On
Public Class Cars
Private strCarMake As String
Private strCarModel As String
Private intYear As String
Private strColor As String
Public Sub New(ByVal bvstrCarMake As String, ByVal bvstrCarModel As String, ByVal bvintYear As String, ByVal bvstrColor As String)
prpCarMake = bvstrCarMake
prpYear = CInt(bvintYear)
prpCarModel = bvstrCarModel
prpColor = bvstrColor
End Sub
Public Property prpCarMake() As String
Get
Return strCarMake
End Get
Set(bvstrCarMake As String)
strCarMake = bvstrCarMake
End Set
End Property
Public Property prpCarModel() As String
Get
Return strCarModel
End Get
Set(bvstrCarModel As String)
strCarModel = bvstrCarModel
End Set
End Property
Public Property prpYear() As Integer
Get
Return CInt(intYear)
End Get
Set(bvintYear As Integer)
intYear = CType(bvintYear, String)
End Set
End Property
Public Property prpColor() As String
Get
Return strColor
End Get
Set(bvstrColor As String)
strColor = bvstrColor
End Set
End Property
Public ReadOnly Property prpIsOld() As Boolean
Get
If prpYear > 2010 Then
Return True
Else
Return False
End If
End Get
End Property
'Public ReadOnly Property prpSSN() As String
'Get
'Return strSSN
'End Get
'End Property
Public Function ReturnFullInfo() As String
Return "Make: " & prpCarMake & " Model: " & prpCarModel & "Year: " & prpYear & "Color: " & prpColor
End Function
End Class

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

Use ProvideProperty as object

I would like to use a class that ProvideProperty as object inside the disigner but it seems I can't use it when the property is an Object. A string works well.
I can set and get within the code but not in the designer.
Big thx
My code :
Imports System.Windows.Forms
Imports System.ComponentModel
<ProvideProperty("Champ", GetType(Control))> _
<ProvideProperty("Valeur", GetType(Control))> _
<ProvideProperty("Comparaison", GetType(Control))> _
Public Class ProprietesEtendues
Implements IExtenderProvider
Public Enum CompareType
Egal
Different
PlusGrand
PlusGrandEgal
PlusPetit
PlusPetitEgal
End Enum
Private _champ As New Dictionary(Of IntPtr, String)
Private _val As New Dictionary(Of IntPtr, Object)
Private _comp As New Dictionary(Of IntPtr, CompareType)
'Propriété Comparaison
Public Function GetChamp(ByVal c As Control) As String
Dim strRetour As String = ""
_champ.TryGetValue(c.Handle, strRetour)
Return strRetour
End Function
<DefaultValue(""), Category("Data"), Description("Ajoute une propriété de type String")> _
Public Sub SetChamp(ByVal c As Control, ByVal value As String)
_champ(c.Handle) = value
End Sub
'Propriété Valeur
Public Function GetValeur(ByVal c As Control) As Object
Dim objRetour As Object = ""
_val.TryGetValue(c.Handle, objRetour)
Return objRetour
End Function
<DefaultValue(""), Category("Data"), Description("Ajoute une propriété de type Object")> _
Public Sub SetValeur(ByVal c As Control, ByVal value As Object)
_val(c.Handle) = value
End Sub
'Propriété Comparaison
Public Function GetComparaison(ByVal c As Control) As CompareType
Dim ctRetour As CompareType = CompareType.Egal
_comp.TryGetValue(c.Handle, ctRetour)
Return ctRetour
End Function
<DefaultValue(CompareType.Egal), Category("Data"), Description("Ajoute une propriété de type CompareType")> _
Public Sub SetComparaison(ByVal c As Control, ByVal value As CompareType)
_comp(c.Handle) = value
End Sub
Public Function CanExtend(ByVal target As [Object]) As Boolean Implements IExtenderProvider.CanExtend
Return True
End Function
End Class
Normaly, you can put at least a string like the Tag property
If a string is good enough then you can apply the [TypeConverter] attribute:
<TypeConverter(GetType(StringConverter))> _
Public Function GetValeur(ByVal c As Control) As Object
Dim objRetour As Object = ""
_val.TryGetValue(c.Handle, objRetour)
Return objRetour
End Function
<DefaultValue(""), Category("Data"), Description("Ajoute une propriété de type Object")> _
<TypeConverter(GetType(StringConverter))> _
Public Sub SetValeur(ByVal c As Control, ByVal value As Object)
_val(c.Handle) = value
End Sub

DirectCast(False, Nullable(Of Boolean)) error

I took some code from a C# project and put it into a converter. The original code was:
(Nullable<bool>)false
and the converter said the VB equivalent is:
DirectCast(False, Nullable(Of Boolean))
I even compiled the C# project and looked at it in Reflector. It gave the same VB code as above, but this generates the error:
Value of type 'Boolean' cannot be converted to 'Boolean?'
How do I cast this properly?
More Code as requested:
Imports System.Windows
Imports System.Windows.Controls.Primitives
Imports System.Windows.Input
Public Class VirtualToggleButton
Public Shared ReadOnly IsCheckedProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsChecked", _
GetType(Nullable(Of Boolean)), _
GetType(VirtualToggleButton), _
New FrameworkPropertyMetadata(DirectCast(False, Nullable(Of Boolean)), _
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault Or _
FrameworkPropertyMetadataOptions.Journal, _
New PropertyChangedCallback(AddressOf OnIsCheckedChanged)))
Public Shared Function GetIsChecked(ByVal d As DependencyObject) As Nullable(Of Boolean)
Return DirectCast(d.GetValue(IsCheckedProperty), Nullable(Of Boolean))
End Function
Public Shared Sub SetIsChecked(ByVal d As DependencyObject, ByVal value As Nullable(Of Boolean))
d.SetValue(IsCheckedProperty, value)
End Sub
Private Shared Sub OnIsCheckedChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim pseudobutton As UIElement = TryCast(d, UIElement)
If pseudobutton IsNot Nothing Then
Dim newValue As Nullable(Of Boolean) = DirectCast(e.NewValue, Nullable(Of Boolean))
If newValue = True Then
RaiseCheckedEvent(pseudobutton)
ElseIf newValue = False Then
RaiseUncheckedEvent(pseudobutton)
Else
RaiseIndeterminateEvent(pseudobutton)
End If
End If
End Sub
Public Shared ReadOnly IsThreeStateProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsThreeState", _
GetType(Boolean), _
GetType(VirtualToggleButton), _
New FrameworkPropertyMetadata(CBool(False)))
Public Shared Function GetIsThreeState(ByVal d As DependencyObject) As Boolean
Return CBool(d.GetValue(IsThreeStateProperty))
End Function
Public Shared Sub SetIsThreeState(ByVal d As DependencyObject, ByVal value As Boolean)
d.SetValue(IsThreeStateProperty, value)
End Sub
Public Shared ReadOnly IsVirtualToggleButtonProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsVirtualToggleButton", _
GetType(Boolean), _
GetType(VirtualToggleButton), _
New FrameworkPropertyMetadata(CBool(False), _
New PropertyChangedCallback(AddressOf OnIsVirtualToggleButtonChanged)))
Public Shared Function GetIsVirtualToggleButton(ByVal d As DependencyObject) As Boolean
Return CBool(d.GetValue(IsVirtualToggleButtonProperty))
End Function
Public Shared Sub SetIsVirtualToggleButton(ByVal d As DependencyObject, ByVal value As Boolean)
d.SetValue(IsVirtualToggleButtonProperty, value)
End Sub
Private Shared Sub OnIsVirtualToggleButtonChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim element As IInputElement = TryCast(d, IInputElement)
If element IsNot Nothing Then
If CBool(e.NewValue) Then
AddHandler element.MouseLeftButtonDown, New MouseButtonEventHandler(AddressOf VirtualToggleButton.OnMouseLeftButtonDown)
AddHandler element.KeyDown, New KeyEventHandler(AddressOf VirtualToggleButton.OnKeyDown)
Else
RemoveHandler element.MouseLeftButtonDown, New MouseButtonEventHandler(AddressOf VirtualToggleButton.OnMouseLeftButtonDown)
RemoveHandler element.KeyDown, New KeyEventHandler(AddressOf VirtualToggleButton.OnKeyDown)
End If
End If
End Sub
Friend Shared Function RaiseCheckedEvent(ByVal target As UIElement) As RoutedEventArgs
If target Is Nothing Then
Return Nothing
End If
Dim args As New RoutedEventArgs()
args.RoutedEvent = ToggleButton.CheckedEvent
[RaiseEvent](target, args)
Return args
End Function
Friend Shared Function RaiseUncheckedEvent(ByVal target As UIElement) As RoutedEventArgs
If target Is Nothing Then
Return Nothing
End If
Dim args As New RoutedEventArgs()
args.RoutedEvent = ToggleButton.UncheckedEvent
[RaiseEvent](target, args)
Return args
End Function
Friend Shared Function RaiseIndeterminateEvent(ByVal target As UIElement) As RoutedEventArgs
If target Is Nothing Then
Return Nothing
End If
Dim args As New RoutedEventArgs()
args.RoutedEvent = ToggleButton.IndeterminateEvent
[RaiseEvent](target, args)
Return args
End Function
Private Shared Sub OnMouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
e.Handled = True
UpdateIsChecked(TryCast(sender, DependencyObject))
End Sub
Private Shared Sub OnKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If e.OriginalSource Is sender Then
If e.Key = Key.Space Then
If (Keyboard.Modifiers And ModifierKeys.Alt) = ModifierKeys.Alt Then
Return
End If
UpdateIsChecked(TryCast(sender, DependencyObject))
e.Handled = True
ElseIf e.Key = Key.Enter AndAlso CBool(TryCast(sender, DependencyObject).GetValue(KeyboardNavigation.AcceptsReturnProperty)) Then
UpdateIsChecked(TryCast(sender, DependencyObject))
e.Handled = True
End If
End If
End Sub
Private Shared Sub UpdateIsChecked(ByVal d As DependencyObject)
Dim isChecked As Nullable(Of Boolean) = GetIsChecked(d)
If isChecked = True Then
SetIsChecked(d, If(GetIsThreeState(d), DirectCast(Nothing, Nullable(Of Boolean)), DirectCast(False, Nullable(Of Boolean))))
Else
SetIsChecked(d, isChecked.HasValue)
End If
End Sub
Private Shared Sub [RaiseEvent](ByVal target As DependencyObject, ByVal args As RoutedEventArgs)
If TypeOf target Is UIElement Then
TryCast(target, UIElement).[RaiseEvent](args)
ElseIf TypeOf target Is ContentElement Then
TryCast(target, ContentElement).[RaiseEvent](args)
End If
End Sub
End Class
It looks like you can just remove the DirectCast. From what I see you are passing a false into a function/method that has a Boolean? (or Nullable(of Boolean)) as a parameter. VB does not need the explicit casting that C# requires (although it's not a bad idea in some cases). For a simple example,
Private Function DoSomething(byval param as Boolean?) as Boolean?
'do something and return a Nullable(of Boolean)
End Function
DoSomething(false) 'is just fine, no DirectCast needed
DoSomething(nothing) 'is also fine
DoSomething(true) 'fine
DoSomething(DirectCast(false, Nullable(of Boolean)) 'will give you the error you described
Just as a side note, in case it is confusing Nullable(of Boolean) and Boolean? mean the same thing which is that it is a boolean variable that can have a value of true, false or nothing.
TKTS is correct that VB normally doesn't need the explicit cast, but, for completeness, the "correct" conversion would be:
New Boolean?(False)