Adding an event handler to custom control - vb.net

I have created a custom control (Check Box) with a custom EventHandler
Public Event CheckedChanged As EventHandler
Private Sub setCheckStateUI(sender As Object, e As EventArgs)
...
RaiseEvent CheckedChanged(sender, e)
End Sub
It works fine without any errors if I added this control directly to a form. But when I add this to another custom control (a page of settings window) and that second custom control add to a form (settings window) the 'settings window' freeze and visual studio auto restart.
If I removed this event handler in the code the problem is gone.
What can be the problem here?
Thanks in advance
Update: (Complete code of the Custom Control)
Public Class cusCheckBox
Private mystring As String
Private CheckButtonState As Integer = 0
Public Event CheckedChanged As EventHandler
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
mystring = Me.Name
setSizes()
End Sub
Public Property CheckState() As Integer
Get
CheckState = CheckButtonState
End Get
Set(ByVal value As Integer)
CheckButtonState = value
chkButton.CheckState = CheckButtonState
End Set
End Property
Public Property LabelText() As String
Get
LabelText = mystring
End Get
Set(ByVal value As String)
mystring = value
lblText.Text = mystring
setSizes()
End Set
End Property
Public Overrides Property Font As Font
Get
Return lblText.Font
End Get
Set(value As Font)
lblText.Font = value
End Set
End Property
Private Sub chkButton_CheckedChanged(sender As Object, e As EventArgs) Handles chkButton.CheckedChanged
If chkButton.CheckState = 1 Then
chkButton.Image = Global.MYLogs.My.Resources.Resources.btnToggleOn
CheckButtonState = 1
Else
chkButton.Image = Global.MYLogs.My.Resources.Resources.btnToggleOff
CheckButtonState = 0
End If
End Sub
Private Sub lblText_Click(sender As Object, e As EventArgs) Handles lblText.Click
setCheckStateUI(sender, e)
End Sub
Private Sub cusCheckBox_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
setCheckStateUI(sender, e)
End Sub
Private Sub cusCheckBox_Load(sender As Object, e As EventArgs) Handles MyBase.Load
setCheckStateUI(sender, e)
setSizes()
End Sub
Private Sub cusCheckBox_Resize(sender As Object, e As EventArgs) Handles Me.Resize
setSizes()
End Sub
Private Sub setSizes()
Me.Size = New Size(chkButton.Width + lblText.Width + 4, chkButton.Height)
End Sub
Private Sub setCheckStateUI(sender As Object, e As EventArgs)
If chkButton.CheckState = 0 Then
chkButton.Image = Global.MYLogs.My.Resources.Resources.btnToggleOn
chkButton.CheckState = 1
CheckButtonState = 1
Else
chkButton.Image = Global.MYLogs.My.Resources.Resources.btnToggleOff
chkButton.CheckState = 0
CheckButtonState = 0
End If
RaiseEvent CheckedChanged(Me, EventArgs.Empty)
chkButton.Select()
End Sub
End Class

Related

Menu Item Custom Control Events

I am trying to create a menu list item that contains both a textbox and a label as a single item. In the code below I have made the necessary custom control class inherited from ToolStripControlHost and this looks and behaves as expected when created in the form menu.
The problem I am having is that the control's events are not firing the handler routine. In the example below, what I would expect to happen is that when the user types into the text box a message should show (other events have the same problem).
Thank you.
Control Classes:
Public Class ToolStripTextBoxWithLabel
Inherits ToolStripControlHost
Public Sub New(Optional ByVal lblText As String = "label")
MyBase.New(New ControlPanel(lblText))
End Sub
Public ReadOnly Property ControlPanelControl() As ControlPanel
Get
Return CType(Me.Control, ControlPanel)
End Get
End Property
End Class
Public Class ControlPanel
Inherits Panel
Friend WithEvents txt As New TextBox
Friend WithEvents lbl As New Label
Public Sub New(ByVal lblText As String)
Me.Height = 20
lbl.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
lbl.Text = lblText
lbl.TextAlign = ContentAlignment.BottomLeft
lbl.AutoSize = True
lbl.Height = Me.Height
lbl.Location = New Point(0, 3)
lbl.Parent = Me
txt.Anchor = AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top
txt.Location = New Point(lbl.Right + 3, 0)
txt.Width = Me.Width - txt.Left
txt.Parent = Me
End Sub
End Class
Form Implementation:
Public Class Form1
Friend tb_SearchBox As ToolStripTextBoxWithLabel
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
tb_SearchBox = New ToolStripTextBoxWithLabel("Search:") With {.Name = "tb_SearchBox"}
AddHandler tb_SearchBox.TextChanged, AddressOf tb_SearchBox_TextChanged
Item1ToolStripMenuItem.DropDownItems.Add(tb_SearchBox)
End Sub
Private Sub tb_SearchBox_TextChanged(sender As Object, e As EventArgs)
MsgBox("Success")
End Sub
End Class
Using the TextChanged event of your ToolStripTextBoxWithLabel in this instance is inappropriate because that event should only be raised when the Text property of that object changes, which is not happening here. You need to do what Plutonix suggested but you should also do it with your own custom event rather than with the TextChanged event of the host, e.g.
Public Event TextBoxTextChanged As EventHandler
Protected Overridable Sub OnTextBoxTextChanged(e As EventArgs)
RaiseEvent TextBoxTextChanged(Me, e)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
OnTextBoxTextChanged(EventArgs.Empty)
End Sub
Rather than deriving your ControlPanel class from Panel and creating the child controls in code, I would suggest that you create a user control and add the children in the designer. You would then use my answer below in two steps, i.e. the user control would handle the TextChanged event of the TextBox and then raise an event of its own that would, in turn, be handled by the ToolStripTextBoxWithLabel that would its own event.
Thanks to jmcilhinney and Plutonix I have put together the solution. For completeness and future community reference the full solution is below.
User Control:
Public Class CustomTextBox
Public Event TextBoxTextChanged As EventHandler
Protected Overridable Sub OnTextBoxTextChanged(e As EventArgs)
RaiseEvent TextBoxTextChanged(Me, e)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
OnTextBoxTextChanged(EventArgs.Empty)
End Sub
Public Sub New (lblText as string)
InitializeComponent()
Caption = lblText
End Sub
Public Property Caption() As String
Get
Return Label1.Text
End Get
Set(ByVal value As String)
Label1.Text = value
End Set
End Property
Public Overrides Property Text() As String
Get
Return TextBox1.Text
End Get
Set(ByVal value As String)
TextBox1.Text = value
End Set
End Property
Public Class
Implementation:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SearchBox As New CustomTextBox("Search")
Dim host As ToolStripControlHost = new ToolStripControlHost(windowNewMenu)
AddHandler SearchBox.TextBoxTextChanged, AddressOf SearchBox_TextChanged
ToolStripMenuItem1.DropDownItems.Add(host)
End Sub
Private Sub SearchBox_TextChanged(sender As Object, e As EventArgs)
MsgBox(sender.Text)
End Sub

Form with UserControl opens in VS2013 but not in VS2015

I have a Windows Form application that was originally created in VS2010. I have since migrated it to VS2013 and VS2015. The Application compiles fine and runs in VS2015, but if I try to open a particular form, the designer crashes giving the following error:
Error HRESULT E_FAIL has been returned from a call to a COM component.
It doesn't give the line of code that caused the error, but it does give a call stack as follows:
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at Microsoft.VisualStudio.LanguageServices.Implementation.Utilities.Exceptions.ThrowEFail()
at Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.CodeTypeRef.LookupTypeSymbol()
at Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.CodeTypeRef.get_TypeKind()
at EnvDTE.CodeTypeRef.get_TypeKind()
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomParser.GetUrtTypeFromVsType(CodeTypeRef vsType)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomParser.OnTypePopulateMembers(Object sender, EventArgs e)
at System.CodeDom.CodeTypeDeclaration.get_Members()
at Microsoft.VisualStudio.Design.Serialization.CodeDom.MergedCodeDomParser.CodeTypeDeclarationPopulator.OnPopulateMembers(Object sender, EventArgs e)
at System.CodeDom.CodeTypeDeclaration.get_Members()
at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)
I am pretty sure it has to do with the fact that I use custom controls on the form. The code for the custom controls is as follows:
Public Class ctlServiceItem
Implements IComponent
Private _SelectedItem As AP_Data.AP_InvoiceService.SelectedItemEnum = AP_Data.AP_InvoiceService.SelectedItemEnum.NA
Public Event SelectedItemChanged As EventHandler
Public Property SelectedItem As AP_Data.AP_InvoiceService.SelectedItemEnum
Get
Return _SelectedItem
End Get
Set(value As AP_Data.AP_InvoiceService.SelectedItemEnum)
_SelectedItem = value
Select Case SelectedItem
Case AP_Data.AP_InvoiceService.SelectedItemEnum.NA
rbNA.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.OK
rbOK.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Replaced
rbReplaced.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Required
rbRequired.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Suggested
rbSuggested.Checked = True
End Select
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Set
End Property
Public Property HeaderText As String
Get
Return GroupBox1.Text
End Get
Set(value As String)
GroupBox1.Text = value
End Set
End Property
Private _Added As Boolean
Public Property Added As Boolean
Get
Return _Added
End Get
Set(value As Boolean)
_Added = value
If _Added Then
rbReplaced.Text = "Added"
Else
rbReplaced.Text = "Replaced"
End If
End Set
End Property
Private Sub rbOK_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbOK.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.OK
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbSuggested_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbSuggested.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Suggested
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbRequired_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbRequired.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Required
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbReplaced_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbReplaced.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Replaced
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbNA_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbNA.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.NA
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
End Class
The other control is
Public Class ctlServiceTireItem
Implements IComponent
Private _SelectedItem As AP_Data.AP_InvoiceService.SelectedItemEnum = AP_Data.AP_InvoiceService.SelectedItemEnum.NA
Public Event SelectedItemChanged As EventHandler
Public Property SelectedItem As AP_Data.AP_InvoiceService.SelectedItemEnum
Get
Return _SelectedItem
End Get
Set(value As AP_Data.AP_InvoiceService.SelectedItemEnum)
_SelectedItem = value
Select Case SelectedItem
Case AP_Data.AP_InvoiceService.SelectedItemEnum.NA
rbNA.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.OK
rbOK.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Replaced
rbReplaced.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Required
rbRequired.Checked = True
Case AP_Data.AP_InvoiceService.SelectedItemEnum.Suggested
rbSuggested.Checked = True
End Select
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Set
End Property
Public Property HeaderText As String
Get
Return GroupBox1.Text
End Get
Set(value As String)
GroupBox1.Text = value
End Set
End Property
Private Sub rbOK_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbOK.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.OK
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbSuggested_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbSuggested.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Suggested
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbRequired_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbRequired.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Required
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbReplaced_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbReplaced.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.Replaced
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
Private Sub rbNA_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbNA.CheckedChanged
_SelectedItem = AP_Data.AP_InvoiceService.SelectedItemEnum.NA
RaiseEvent SelectedItemChanged(Me, EventArgs.Empty)
End Sub
End Class
I can provide the designer code for the form if needed, but it is voluminous. The controls show up in the toolbox as Project controls just like they should. It just doesn't make sense that it will open in the designer fine in one version of VS but not the newer version. Since it does work in an earlier version I was really hoping it is just an obscure setting or something like that.
Update: I tried creating a brand new blank form. I was able to drag the controls over to the new form and they showed up fine. When I closed the form and re-opened it in the designer, I got the same error as above. The problem is definitely with the user controls.
I found the answer at the bottom of
https://social.msdn.microsoft.com/Forums/en-US/97bfbff4-651c-47e4-8aaa-25fa2273b1b5/designer-crash-in-vs2015-in-windows-forms?forum=winformsdesigner
For some reason, I had a referenced to my own project in the project. I think this was a trick to make projects recognize their own controls in earlier versions of Visual Studio. Looks like this was fixed in VS 2015. Once the project didn't have a reference to itself, the Forms with the User Controls showed up fine.

Random delay in seconds from numericupdown in VB.Net

I have a desktop winforms app code:
Sub Delay(ByVal dblSecs As Double)
Const OneSec As Double = 1.0# / (1440.0# * 60.0#)
Dim dblWaitTil As Date
Now.AddSeconds(OneSec)
dblWaitTil = Now.AddSeconds(OneSec).AddSeconds(dblSecs)
Do Until Now > dblWaitTil
Application.DoEvents()
Loop
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Webbrowser1.Navigate(TextBox1.Text)
Delay(Val(DelayText.Text))
end sub
What I need is to set max. delay, same from textbox by entering seconds.
I need this to be random delay number so Im stacking here, thanks for correcting my code.
Also If its possible to make it in NumericUpDown, as i found some topics which says textbox text property is different as NumericUpDown but i like it more.
You could use an inbetween class which does most of the work for you
This class would take the WebBrowser, attach to some events of it, and would refresh periodically (depending on MinimumWait / MaximumWait)
As it is using threading, it also checks if the usercontrol needs to be invoked to Refresh it and when yes, invokes the custom refresh delegate
Public Class Refresher
Protected Delegate Sub RefreshNavigationDelegate(browser As WebBrowser)
Protected Sub RefreshNavigation(browser As WebBrowser)
If browser.InvokeRequired Then
browser.Invoke(New RefreshNavigationDelegate(AddressOf RefreshNavigation), browser)
Return
End If
browser.Refresh(WebBrowserRefreshOption.Completely)
End Sub
Private _isBusy As Boolean = False
Public Property IsBusy As Boolean
Get
Return _isBusy
End Get
Protected Set(value As Boolean)
If _isBusy = value Then
Return
End If
_isBusy = value
End Set
End Property
Public Property MinimumWait As Integer = 2000
Public Property MaximumWait As Integer = 10000
Private refreshThread As Thread = Nothing
Private _browser As WebBrowser
Public Property Browser As WebBrowser
Get
Return _browser
End Get
Set(value As WebBrowser)
If Object.Equals(_browser, value) Then
Return
End If
StopRefresh()
If _browser IsNot Nothing Then
RemoveHandler Browser.DocumentCompleted, AddressOf DocumentComplete
RemoveHandler Browser.Navigating, AddressOf Navigating
End If
_browser = value
If _browser IsNot Nothing Then
AddHandler Browser.DocumentCompleted, AddressOf DocumentComplete
AddHandler Browser.Navigating, AddressOf Navigating
AddHandler Browser.ProgressChanged, AddressOf ProgressChanged
End If
StartRefresh()
End Set
End Property
Protected Sub ProgressChanged(sender As Object, e As WebBrowserProgressChangedEventArgs)
IsBusy = e.CurrentProgress > 0 AndAlso e.CurrentProgress < e.MaximumProgress
End Sub
Protected Sub DocumentComplete(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
IsBusy = False
End Sub
Protected Sub Navigating(sender As Object, e As WebBrowserNavigatingEventArgs)
IsBusy = True
End Sub
Public Sub StartRefresh()
If refreshThread IsNot Nothing Then
Return
End If
refreshThread = New Thread(AddressOf DoRandomRefreshes)
refreshThread.Start()
End Sub
Public Sub StopRefresh()
If refreshThread Is Nothing Then
Return
End If
refreshThread.Abort()
refreshThread = Nothing
End Sub
Protected Overridable Sub DoRandomRefreshes()
Dim randomGenerator As New Random()
While Not refreshThread.ThreadState = ThreadState.AbortRequested
Dim newTimeout As Integer = MinimumWait + randomGenerator.Next(MaximumWait - MinimumWait)
Thread.Sleep(newTimeout)
If Not IsBusy Then
RefreshNavigation(Browser)
End If
End While
End Sub
Public Sub New()
End Sub
End Class
You could then use it in your form as such:
Public Class Form1
Dim myRefresher As Refresher = New Refresher()
Private Sub tsbGo_Click(sender As Object, e As EventArgs) Handles tsbGo.Click
WebBrowser1.Navigate(txtUrl.Text)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myRefresher.Browser = WebBrowser1
End Sub
Private Sub txtMin_TextChanged(sender As Object, e As EventArgs) Handles txtMin.TextChanged
Dim int As Integer = 0
If Integer.TryParse(txtMin.Text, int) Then
myRefresher.MinimumWait = int
End If
End Sub
Private Sub txtMax_TextChanged(sender As Object, e As EventArgs) Handles txtMax.TextChanged
Dim int As Integer = 0
If Integer.TryParse(txtMax.Text, int) Then
myRefresher.MaximumWait = int
End If
End Sub
End Class

Cancel Datetimepicker ValueChanged Event

Is there a way to cancel an event through a condition? I have tried e.cancel but it does not work. After cancelling the event the dtpAudit_From.Value must revert back to its original value.
Private Sub dtpAudit_From_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpAudit_From.ValueChanged
'check if two DTPs (Date time pickers) are valid
If dtpAudit_From.Value > dtpAudit_To.Value Then
MsgBox("cancel the event")
End If
End Sub
One way is to subclass the DateTimePicker and add a ValueChanging event. Here's an example:
Public Class UIDateTimePicker
Inherits DateTimePicker
Public Sub New()
Me.cachedValue = Me.Value
End Sub
Public Event ValueChanging As CancelEventHandler
Protected Overrides Sub OnValueChanged(e As EventArgs)
If (Not Me.reverting) Then
Dim evargs As New CancelEventArgs(False)
Me.OnValueChanging(evargs)
If ((Not evargs Is Nothing) AndAlso evargs.Cancel) Then
Dim value As Date = Me.Value
Me.reverting = True
Me.Value = Me.cachedValue
Else
Me.cachedValue = Value
MyBase.OnValueChanged(e)
End If
Me.reverting = False
End If
End Sub
Protected Overridable Sub OnValueChanging(e As CancelEventArgs)
RaiseEvent ValueChanging(Me, e)
End Sub
Private cachedValue As DateTime
Private reverting As Boolean
End Class
Usage
Private Sub dtpAudit_From_ValueChanging(sender As Object, e As CancelEventArgs) Handles dtpAudit_From.ValueChanging
e.Cancel = {Condition}
End Sub

Making combobox visible when it is disabled

I am disabling combobox in VB.net.
But in disable mode it not visible properly.
I tried changing both BackColor and ForeColor but it is not working.
Code :
cmbbox.BackColor = Color.FromName("Window")
or
cmbbox.ForeColor = Color.FromName("Window")
Please help
Dear Adam:
I am making my component enable false.But I want to make it viewable.You can reffer the link.This is what exacly I want but in VB.Net : A combobox that looks decent when it is disabled
To achieve disabling combobox without fading it, first change the dropdown style of the combobox to DropDownList, Then tweak with the events to achieve the goal.
Here is a piece of code by which you can achieve the same:
Public Class Form1
Dim selectindex As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("1")
ComboBox1.Items.Add("2")
ComboBox1.Items.Add("3")
ComboBox1.Items.Add("4")
selectindex = 3
ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
ComboBox1.SelectedIndex = selectindex
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox1.SelectedIndex = selectindex
End Sub
End Class
Create anew form Form1 and add a combobox to the form, then add the above code to get a readonly combobox.
Have a look at this thread which has a solution for a readonly combobox and the code is all VB.NET.
A version of their code is as follows. You'll need to but it inside a class of your own which inherits System.Windows.Forms.ComboBox
Private _ReadOnly As Boolean = False
Public Property [ReadOnly]() As Boolean
Get
Return _ReadOnly
End Get
Set(ByVal Value As Boolean)
_ReadOnly = Value
End Set
End Property
Public Overrides Function PreProcessMessage(ByRef msg As Message) As Boolean
'Prevent keyboard entry if control is ReadOnly
If _ReadOnly = True Then
'Check if its a keydown message
If msg.Msg = &H100 Then
'Get the key that was pressed
Dim key As Int32 = msg.WParam.ToInt32
'Ignore navigation keys
If key = Keys.Tab Or key = Keys.Left Or key = Keys.Right Then
'Do nothing
Else
Return True
End If
End If
End If
'Call base method so delegates receive event
Return MyBase.PreProcessMessage(msg)
End Function
Protected Overrides Sub WndProc(ByRef m As Message)
'Prevent list displaying if ReadOnly
If _ReadOnly = True Then
If m.Msg = &H201 OrElse m.Msg = &H203 Then
Return
End If
End If
'Call base method so delegates receive event
MyBase.WndProc(m)
End Sub
I've been looking for the same not long ago and ended up doing the following. You may not like it, but i'll share it in case. I am using TableLayoutPanel to arrange my controls on the form and then i am swapping the positions of the desired controls.
For example I've created the following Items:
Form1 Design
TableLayoutPanel1 (two columns, three rows)
TextBox1 Read-only = True, BackColor = White
ComboBox1 Visible = False, DropDownStyle = DropDownList, FlatStyle = Popup
Button1 (named it to Change)
Button2 (named it to Done) -> Visible = False
Runtime - Screenshots
Here is my code:
Public Class Form1
Private Sub SwapControls(tlp As TableLayoutPanel, ctr1 As Control, ctr2 As Control)
Dim ctl1pos As TableLayoutPanelCellPosition = tlp.GetPositionFromControl(ctr1)
ctr1.Visible = False
tlp.SetCellPosition(ctr1, tlp.GetPositionFromControl(ctr2))
ctr2.Visible = True
tlp.SetCellPosition(ctr2, ctl1pos)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SwapControls(TableLayoutPanel1, TextBox1, ComboBox1)
SwapControls(TableLayoutPanel1, Button1, Button2)
Label1.Select()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SwapControls(TableLayoutPanel1, ComboBox1, TextBox1)
SwapControls(TableLayoutPanel1, Button2, Button1)
Label1.Select()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Select()
ComboBox1.SelectedIndex = 0
TextBox1.Text = ComboBox1.SelectedItem
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
End Sub
End Class