Double click form event VB.NET - vb.net

I'm using VB.NET and would like to know how I can double click a form to minimize it.
I have the following code but it does'nt work:
Private Sub openPROJECTS_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseDoubleClick
'Minimize the form
Me.WindowState = FormWindowState.Minimized
End Sub
I'm using VB.NET.

The problem is that every control has it's own double click event, so if you double click e.g. a panel on your form, your form's double click event won't get fired.
You could, however, add a MessageFilter, e.g.
Public Class Minimizer
Implements IMessageFilter
Private Const WM_LBUTTONDBLCLK As Integer = &H203
ReadOnly _form As Form
Public Sub New(f As Form)
_form = f
End Sub
Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
If m.Msg = WM_LBUTTONDBLCLK Then
_form.WindowState = FormWindowState.Minimized
End If
Return False
End Function
End Class
And a little test:
Private Sub Main()
Dim f = New Form()
f.Controls.Add(New Panel() With { .Dock = DockStyle.Fill })
Application.AddMessageFilter(New Minimizer(f))
f.ShowDialog()
End Sub
But I think it would be a strange user experience if double clicking anywhere minimizes the form...

Related

Getting Event Handler from Instance of Class

I'm just getting started with custom classes so I wrote a button strip. It inherits a panel and populates it with buttons from strings passed to my .Add().
ButtonStrip1.Add("Button","Texts","Go Here")
I'd like for it to be able to naturally grab ButtonStrip1.Click's handler and pass it on to child buttons and delete it from ButtonStrip1.
I haven't been able to figure that out, so I've been doing
Public Class ButtonStrip
Inherits Panel
Public Property Innermargin As Integer = 5
Dim Offset As Integer = Innermargin
Dim Buttons = New List(Of ButtonStrip_Button)
Dim StoredFN As EventHandler
Public Sub New()
End Sub
Function Add(fn As EventHandler, ParamArray ByVal Values As String())
StoredFN = fn
For Each V In Values
Dim B As New ButtonStrip_Button
Buttons.Add(B)
Me.Controls.Add(B)
B.Text = V
B.Left = Offset + Innermargin
B.Top = Innermargin
Offset = B.Left + B.Width
AddHandler B.Click, fn
Next
RemoveHandler Me.Click, fn
Me.Width = Offset + Innermargin
Me.Height = Buttons(0).height + Innermargin * 2
End Function
Function Add(ParamArray ByVal Values As String())
If StoredFN Is Nothing Then
Throw New Exception("First Add() must supply a function")
End If
Me.Add(StoredFN, Values)
End Function
End Class
Public Class ButtonStrip_Button
Inherits System.Windows.Forms.Button
Public Sub New()
AutoSize = True
AutoSizeMode = AutoSizeMode.GrowAndShrink
End Sub
End Class
which is called by
ButtonStrip1.Add(AddressOf ButtonStrip1_Click,"Button","Texts","Go Here")
What I'd basically like to do is (psuedo-code)
Function Add(fn As EventHandler, ParamArray ByVal Values As String())
If StoredFN is Nothing Then StoredFN = Me.Click
...
AddHandler B.Click, Me.Click
Next
RemoveHandler Me.Click, Me.Click
...
End Function
I've tried changing a few things and googled a lot. I've also tried using CallByName(Me,"Click",CallType.Method) and with CallType.Get, but the error I get is Expression 'Click' is not a procedure, but occurs as the target of a procedure call. It also returns this exact same message for unhandled events, such as ButtonStrip1 has no MouseDown Event.
I've also tried using MyClass.
Not seen here is an alternative .Add() that add StoredFN to B.click
For instance, this click event works with my code
Private Sub ButtonStrip1_Click(sender As Object, e As EventArgs) Handles ButtonStrip1.Click
msgbox("You clicked " & sender.text & ".")
End Sub
What I was suggesting was something like this:
Public Class ButtonStrip
Inherits Panel
Public Event ButtonClick As EventHandler(Of ButtonClickEventArgs)
Protected Overridable Sub OnButtonClick(e As ButtonClickEventArgs)
RaiseEvent ButtonClick(Me, e)
End Sub
Private Sub Buttons_Click(sender As Object, e As EventArgs)
OnButtonClick(New ButtonClickEventArgs(DirectCast(sender, Button)))
End Sub
Public Sub Add(ParamArray values As String())
Dim btn As New Button
AddHandler btn.Click, AddressOf Buttons_Click
'...
End Sub
End Class
Public Class ButtonClickEventArgs
Inherits EventArgs
Public ReadOnly Property Button As Button
Public Sub New(button As Button)
Me.Button = button
End Sub
End Class
Now there's no need to pass event handlers around. When a Button is clicked, the ButtonStrip handles that event and then raises its own ButtonClick event. Neither the ButtonStrip nor the Buttons have to care about any methods that handle that event as it will be handled the same way any other event is. In a form, you'd then handle the ButtonClick event of the ButtonStrip and get the Button that was clicked from e.Button. You could also add an Index property if you wanted to know the position of the Button rather than the Button itself.

Set the textbox value of usercontrol from Main winForm Button

I have a main Form 'frmMaster' that contains on one button 'btnSet',
inside this main form I put a panel control contains on usercontrol,
on this user control there is one textbox,
my question is how to set the value of this textbox when I click on the button 'btnset' from main form,
for example: when I click on 'btnset' from main form, the value of textbox on the usercontrol will be "Welcome"
In userControl I Put:
Public Property TextBoxTxt () As String
Get
Return txtText1.Text
End Get
Set(value As String)
txtText1.Text = value
End Set
End Property
On Main Form I Put inside button:
Dim uc As New ucControl1
uc.txtText1.Text= "Welcome!"
Your UserControl Must be like :
Public Class UserControl1
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Property TextBoxTxt() As String
Get
Return txtText1.Text
End Get
Set(value As String)
txtText1.Text = value
End Set
End Property
End Class
In you MainForm add a button "btnSet" and a Panel "Panel1" ,so your code inside MainForm must be like :
Public Class frmMaster
Private Sub btnSet_Click(sender As Object, e As EventArgs) Handles btnSet.Click
Dim uc As New UserControl1
uc.txtText1.Text = "Welcome!"
Panel1.Controls.Add(uc)
End Sub
Private Sub frmMaster_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
I have create a simple exemple for you
In the user control:
Public Property TextBoxTxt () As String
Get
Return Me.textbox.Text
End Get
Set(value As String)
Me.txtebox.Text = value
End Set
End Property
In your even click of the button 'btnset' :
Private Sub btnset_Click(sender As Object, e As EventArgs) Handles btnset.Click
Dim uc As New MyUserControl
uc.TextBoxTxt ="Welcome!"
End Sub
You will need to add a public property to the usercontrol, e.g.
Public Property TextBoxMessage As String
Get
Return textbox.Text
End Get
Set(ByVal value As String)
textbox.Text = value
End Set
End Property
Then you can display a message from inside your frmMaster:
usercontrol.TextBoxMessage = "Welcome!"

change GroupControl visibility of opened usercontrol from the form vb.net

I have one 'UserControl' that opened inside form,
this usercontrol has a 'GroupControl'
how can I make this 'GroupControl' hidden or visible when user click on a button that beings on the form
using vb.net
In the user control:
Public Property GroupControlVisible() As Boolean
Get
Return Me.GroupControl1.Visible
End Get
Set(value As Boolean)
Me.GroupControl1.Visible = value
End Set
End Property
Try this :
In you UserControl add a procedure how set visibility to your GroupControl :
Public sub SetVisibility (V as boolean)
YourGroupControl.visible=v
End Sub
In your form
Public Class Form1
Dim uc As New MyUserControl
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Controls.Add(uc)
uc.Dock()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
uc.SetVisibility(False)
'NB :MyUserControl is name of your usercontrol
End Sub
End Class
To Simplify, you can use :
MyParentForm.UserControlName1.GroupControlName.Visible = False
or
CType(MyParentForm.Controls("UserControlName").Controls("GroupControlName"), _
GroupControl).Visible = False
But the best way is create a property which allows changing the Visible property of the GroupControl in UserControl Class like this :
Public Property GroupControlVisibility() As Boolean
Get
Return Me.GroupControlName.Visible
End Get
Set(value As Boolean)
Me.GroupControlName.Visible = value
End Set
End Property

AddressOf with parameter

One way or another I need to link groupID (and one other integer) to the button I am dynamically adding.. any ideas?
What I can do;
AddHandler mybutton.Click, AddressOf PrintMessage
Private Sub PrintMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("Dynamic event happened!")
End Sub
What I can't do, but want to;
AddHandler mybutton.Click, AddressOf PrintMessage(groupID)
Private Sub PrintMessage(ByVal groupID as Integer)
MessageBox.Show("Dynamic event happened!" & groupID .tostring)
End Sub
There is no way to do this with AddressOf itself. What you're looking for is a lambda expression.
AddHandler myButton.Click, Function(sender, e) PrintMessage(groupId)
Private Sub PrintMessage(ByVal groupID as Integer)
MessageBox.Show("Dynamic event happened!" & groupID .tostring)
End Sub
You can create your own button class and add anything you want to it
Public Class MyButton
Inherits Button
Private _groupID As Integer
Public Property GroupID() As Integer
Get
Return _groupID
End Get
Set(ByVal value As Integer)
_groupID = value
End Set
End Property
Private _anotherInteger As Integer
Public Property AnotherInteger() As Integer
Get
Return _anotherInteger
End Get
Set(ByVal value As Integer)
_anotherInteger = value
End Set
End Property
End Class
Since VB 2010 you can simply write
Public Class MyButton
Inherits Button
Public Property GroupID As Integer
Public Property AnotherInteger As Integer
End Class
You can access the button by casting the sender
Private Sub PrintMessage(ByVal sender As Object, ByVal e As EventArgs)
Dim btn = DirectCast(sender, MyButton)
MessageBox.Show( _
String.Format("GroupID = {0}, AnotherInteger = {1}", _
btn.GroupID, btn.AnotherInteger))
End Sub
These new properties can even be set in the properties window (under Misc).
The controls defined in the current project automatically appear in the toolbox.
Use the Tag property of the button.
Button1.Tag = someObject
AddressOf gets the address of a method, and thus you cannot pass parameters to it.
You can use delegate which very clear for your code follow as:
Define a delegate
Public Delegate Sub ControlClickDelegate(ByVal sender As Object, ByVal e As EventArgs)
Custom button class
Public Class CustomButton
Inherits System.Windows.Forms.Button
#Region "property delegate"
Private controlClickDelegate As ControlClickDelegate
Public Property ClickHandlerDelegate As ControlClickDelegate
Get
Return controlClickDelegate
End Get
Set(ByVal Value As ControlClickDelegate)
controlClickDelegate = Value
End Set
End Property
#End Region
Public Sub RegisterEventHandler()
AddHandler Me.Click, AddressOf OnClicking
End Sub
Private Sub OnClicking(ByVal sender As Object, e As System.EventArgs)
If (Me.controlClickDelegate IsNot Nothing) Then
Me.controlClickDelegate(sender, e)
End If
End Sub
End Class
MainForm
Public Class MainForm
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.CusButton1.ClickHandlerDelegate = AddressOf Me.btnClick
Me.CusButton1.RegisterEventHandler()
End Sub
Private Sub btnClick(ByVal sender As Object, ByVal e As EventArgs)
Me.TextBox1.Text = "Hello world"
End Sub
End Class
The below worked for me:
Dim bStart = New Button With {.Text = "START"}
AddHandler bStart.Click, Function(sender, e) TriggerProcess(any Long value)
Private Function TriggerProcess(ByVal paramName As Long) As Boolean
' any processing logic
Return True
End Function
My solution:
AddHandler menuItemYear.Items(i).MouseUp, Sub() menu_year(2019)
Private Sub menu_year(ByVal intYear As Integer)
'do something
End Sub
There are few ways to do that depending of the complexity and number of parameters required.
1. Use Tag for adding a complex structure
2. Inherit the the Button class and add the values as class members then populate them before using it. That gives you a lot more flexibility.
If you are using web version
3. You cannot add it to Tag, but for simple values assign it to index use .Attributes.Add("name"). This gets added to the HTML tags and not the Server side. You can then use the index to access a server side structure for complex systems.
4. Use sessions to store values and store the session reference to Name attribute as described above (#3).
No problem ;-)
For example:
Private ComboActionsOnValueChanged As New Dictionary(Of ComboBox, EventHandler)
'somewhere in function
dim del = Sub(theSender, eventArgs)
MsgBox(CType(theSender, ComboBox).Name & " test")
End Sub
ComboActionsOnValueChanged.Add(myCombo, del)
'somewhere else
Dim delTest = ComboActionsOnValueChanged(myCombo)
RemoveHandler myCombo.SelectedValueChanged, delTest
myCombo.DataSource = someDataSource
AddHandler myCombo.SelectedValueChanged, delTest
as we expect, event won't fire after DataSource change in this place

Why is this blocking? (VB.NET multithreading with events and delegates)

I have a feature whereby a class in a dll displays a form asking a user to clear a fault on a printer before clicking a button to say "Retry". The users have been just hitting retry without bothering to clear the fault so I am now coding an interlock:
The button on the invoked form is disabled until a call is made to an 'enable' method on the form.
This is done with delegate invocation as the events triggering these changes come from other dlls running on different threads.
The form's 'enable' method is wired into an EVENT HANDLER handling an event coming in from a different thread (one that monitors an ethernet IO Server).
The problem I have is that THE "_Fault_StateChanged" EVENT NEVER FIRES. I suspected the cause was the "ShowDialog" and "DialogResult" technique I have used here, but I have used this exact same technique elsewhere in this application.
Any suggestions would be great
See code extract below:
MAIN CLASS excerpt
Public Class StatePrintHandler
Private WithEvents _RetryForm As frmRetryReject
Private Delegate Sub delShowRetryDialog()
Private Delegate Sub delResetEnable()
Private Sub InvokeResetEnable()
Dim del As delResetEnable
del = New delResetEnable(AddressOf ResetEnable)
del.Invoke()
End Sub
Private Sub InvokeRetryDialogue()
Dim del As delShowRetryDialog
del = New delShowRetryDialog(AddressOf ShowRetryDialog)
del.Invoke()
End Sub
Private Sub ShowRetryDialog()
_RetryForm = New frmRetryReject
_RetryForm.Prep()
_RetryForm.ShowDialog()
If (_RetryForm.DialogResult = Windows.Forms.DialogResult.OK) Then
Me._RetryForm.Visible = False
End If
End Sub
Private Sub ResetEnable()
If (Not IsNothing(_RetryForm)) Then
_RetryForm.ResetEnable()
Else
AuditTrail("Retry form not active, no action", True)
End If
End Sub
'Event handler for status change coming in on a different thread
Private Sub _Fault_StateChanged(ByVal sender As Object, ByVal e As Drivers.Common.DigitalSignalChangedEventArgs) Handles _fault.StateChanged
If (e.NewState) Then
AuditTrail("Labeller has faulted out during cycling", True)
Else
InvokeResetEnable()
End If
End Sub
End Class
RETRY FORM CLASS excerpt
Public Class frmRetryReject
Private Delegate Sub delEnable()
Public Event Complete()
Public Sub Prep()
Me.OK_Button.Enabled = False
End Sub
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Public Sub ResetEnable()
If (IsHandleCreated) Then
Dim params() As Object = {}
Me.Invoke(New delEnable(AddressOf InvokeEnable), params)
End If
End Sub
Private Sub InvokeEnable()
Me.OK_Button.Enabled = True
End Sub
End Class
Additional detail in response to Daniel's comments
The code is incomplete here, it's an excerpt. The fault object is a subscription to an external library and is a handler for an ethernet IO server.
The _fault StateChanged event fires when a digital input on an IOServer changes. I know the following:
My trace files show the signal change high, this invokes the retry form.
The signal physically changes low again when the retry screen is still showing.
...but the event does not fire
It's as if the application cannot service the event coming in until the ShowDialog/DialogResult completes - but I am confused about this because I understood that the ShowDialog in .NET 2.0 did not block, I should still be able to service events, and have used this same pattern elsewhere in the app.
A couple of things to note:
The MAIN CLASS is instantiated dynamically at runtime via reflection based on configuration.
This is VS2005 SP2
I will post the entire class in another code box if this helps, but it may crowd the scene...
Thanks
Andy
Imports System.IO
Imports ACS.Interfaces
Imports ACS.Pallet
Public Class StateCimPAKPrintHandler
Inherits StateBase
Private WithEvents _ioManager As ACS.Components.DigitalIOManager
Private _config As StateCimPAKPrintHandlerBootstrap
Private CONST_OutcomeOK As String = "OK"
Private CONST_OutcomeRetry As String = "Retry"
Private CONST_OutcomeException As String = "Exception"
Private WithEvents _busy As ACS.Drivers.Common.InputSignal
Private WithEvents _fault As ACS.Drivers.Common.InputSignal
Private WithEvents _print As ACS.Drivers.Common.OutputSignal
Private WithEvents _palletRelease As ACS.Drivers.Common.OutputSignal
Private _labellingInProgress As Boolean
Private _faulted As Boolean
Private _retryScreenInvoked As Boolean
Private WithEvents _timeout As System.Timers.Timer
Private WithEvents _faultTimer As System.Timers.Timer
Private WithEvents _RetryForm As frmRetryReject
Private Delegate Sub delShowRetryDialog()
Private Delegate Sub delResetEnable()
Private Sub InvokeResetEnable()
Dim del As delResetEnable
del = New delResetEnable(AddressOf ResetEnable)
del.Invoke()
End Sub
Private Sub InvokeRetryDialogue()
Dim del As delShowRetryDialog
del = New delShowRetryDialog(AddressOf ShowRetryDialog)
del.Invoke()
End Sub
Private Sub ShowRetryDialog()
_timeout.Stop()
_retryScreenInvoked = True
_RetryForm = New frmRetryReject
_RetryForm.Prep()
AuditTrail("Displaying Retry screen", True)
_RetryForm.ShowDialog()
If (_RetryForm.DialogResult = Windows.Forms.DialogResult.OK) Then
AuditTrail("User clicked RETRY LINE on the RETRY dialogue", True)
_retryScreenInvoked = False
Me._RetryForm.Visible = False
Me.SetOutcome(CONST_OutcomeRetry)
End If
End Sub
Private Sub ResetEnable()
If (Not IsNothing(_RetryForm)) Then
_RetryForm.ResetEnable()
Else
AuditTrail("Retry form not active, no action", True)
End If
End Sub
Public Sub New(ByVal Sequencer As ISequencer, ByVal ParentPlt As ACS.Interfaces.IPallet, ByVal Name As String)
MyBase.New(Sequencer, ParentPlt, Name)
_timeout = New System.Timers.Timer
_faultTimer = New System.Timers.Timer
_config = New StateCimPAKPrintHandlerBootstrap(Me._myIniFileName, Name)
_timeout.Interval = _config.CycleTimeoutMS
_faultTimer.Interval = 750
_retryScreenInvoked = False
_RetryForm = New frmRetryReject
Me._RetryForm.Visible = False
_ioManager = ACS.Components.DigitalIOManager.GetInstance
_busy = _ioManager.GetInput("Busy")
_fault = _ioManager.GetInput("CimPAKFault")
_print = _ioManager.GetOutput("Print")
_palletRelease = _ioManager.GetOutput("PalletRelease")
End Sub
Public Overrides Sub Kill()
_ioManager = Nothing
_RetryForm = Nothing
_busy = Nothing
_fault = Nothing
_print = Nothing
_timeout = Nothing
_faultTimer = Nothing
_pallet = Nothing
End Sub
Public Overrides Sub Execute()
AuditTrail("Pulsing Print Signal", True)
_print.PulseOutput(3000)
_labellingInProgress = True
_timeout.Start()
End Sub
Private Sub _busy_StateChanged(ByVal sender As Object, ByVal e As Drivers.Common.DigitalSignalChangedEventArgs) Handles _busy.StateChanged
_timeout.Stop()
AuditTrail("Busy signal changed to : " & e.NewState, True)
If (e.NewState) Then
_faulted = False
AuditTrail("CimPAK = Busy High", True)
_labellingInProgress = True
Else
AuditTrail("CimPAK = Busy Low", True)
AuditTrail("Wait 750 milliseconds for any faults", True)
_faultTimer.Start()
End If
End Sub
Private Sub _Fault_StateChanged(ByVal sender As Object, ByVal e As Drivers.Common.DigitalSignalChangedEventArgs) Handles _fault.StateChanged
AuditTrail("Fault signal changed to : " & e.NewState, True)
If (e.NewState) Then
If (_labellingInProgress = True) Then
AuditTrail("Labeller has faulted out during cycling", True)
_faulted = True
If (Not _retryScreenInvoked) Then
InvokeRetryDialogue()
End If
Else
AuditTrail("Labeller has faulted out between cycles, no action can be taken", True)
End If
Else
If (_retryScreenInvoked) Then
AuditTrail("Enable button on Retry screen", True)
InvokeResetEnable()
End If
_faulted = False
End If
End Sub
Private Sub _faultTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _faultTimer.Elapsed
_faultTimer.Stop()
If (_faulted) Then
AuditTrail("System has faulted", True)
Else
AuditTrail("No fault occured, assume pallet is OK to release", True)
AuditTrail("CimPAK cycle complete", True)
_labellingInProgress = False
_palletRelease.PulseOutput(3000)
Me.SetOutcome(CONST_OutcomeOK)
End If
End Sub
Private Sub _timeout_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timeout.Elapsed
_timeout.Stop()
AuditTrail("Labeller print cycle timed out", True)
If (Not _retryScreenInvoked) Then
_retryScreenInvoked = True
InvokeRetryDialogue()
InvokeResetEnable()
End If
End Sub
End Class
#Region "Bootstrap"
Public Class StateCimPAKPrintHandlerBootstrap
Private Const CONST_CycleTimeoutMS As String = "CycleTimeoutMS"
Private _CycleTimeoutMS As Long
#Region "Properties"
Public ReadOnly Property CycleTimeoutMS() As Long
Get
Return _CycleTimeoutMS
End Get
End Property
#End Region
Public Sub New(ByVal IniFile As String, ByVal Name As String)
Try
Dim _cfgFile As String = Environ("ACSVAR") & "\" & IniFile
' Check to see if the CFG file exits
If File.Exists(_cfgFile) = False Then
Throw New Exception("Configuration file does not exist: " & _cfgFile)
Else
'Get values
_CycleTimeoutMS = ACS.Utility.Configuration.GetLong(_cfgFile, Name, CONST_CycleTimeoutMS)
End If
Catch ex As Exception
Throw
End Try
End Sub
End Class
#End Region
Try to look at
Visual Basic, Child Thread Blocking Main Thread
answer for in Multithreading example and
New Thread is still blocking UI-Thread
answer from ( me ) for In Model Threading.... Those 2 should give you writen code to start aswell.
It's been a long time since I did any Winforms work, but are you showing the dialog modally? Because that could be the cause of the delegate invokation not arriving.
Asynchronous delegates work by serializing the invokation details into a memory location internal to the framework and then posting a window message to the top-level window for the relevant thread. Modal dialogs work by going into a message processing loop that steals all the messages for the thread so that only that one dialog can respond. You can see how this might conflict.