How to give a "ctrl + " shortcut key for a button in vb.net - vb.net

how to add a " ctrl + " shortcut to button in vb.net. For example I need to perform click event of save button when ctrl + s is pressed.

Winforms Solution
In your Form class, set its KeyPreview property to true, example of it being set in the Form constructor, either set it here or via the Designer:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.KeyPreview = True
End Sub
Then all you need to do is handle the KeyDown event for the Form, like this:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
If (e.Control AndAlso e.KeyCode = Keys.S) Then
Debug.Print("Call Save action here")
End If
End Sub
WPF Solution (Not using MVVM pattern)
Add this to your .xaml file
<Window.Resources>
<RoutedUICommand x:Key="SaveCommand" Text="Save" />
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource SaveCommand}" Executed="SaveAction" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="S" Modifiers="Ctrl" Command="{StaticResource SaveCommand}" />
</Window.InputBindings>
Alter your button definition to include Command="{StaticResource SaveCommand}", for example:
<Button x:Name="Button1" Content="Save" Command="{StaticResource SaveCommand}" />
In your Code Behind (.xaml.vb) put your function to call the save routine, such as:
Private Sub SaveAction(sender As Object, e As RoutedEventArgs)
Debug.Print("Call Save action here")
End Sub

Related

Add logic inside button click inside a custom control

I am making a custom control that looks like this (there is a label on the right of the button):
I want the user to be able to define what the button does in his code, but still execute some code on the click event on top of the user's code.
What I want to execute :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Button1.Enabled = False
Label1.ForeColor = Color.Gray
Label1.Text = "In Progress"
End Sub
then after this is executed the user's on click event would trigger.
How can I achieve this?
With "the user" you mean a developer which uses that user control, right? Well, the most common thing is to raise an event which the next developer can use to implement his own logic. This is exactly the same as you do - you use the Click-Event of the button.
So basically, take your code and add the RaiseEvent below:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Button1.Enabled = False
Label1.ForeColor = Color.Gray
Label1.Text = "In Progress"
' this does not affect your code but provides a "hook" for
' other developers
RaiseEvent OnButtonClick(Button1)
End Sub
Now you need to define the event itself like this ...
Public Event OnButtonClick(ByVal sender As Control)
... btw, you can pass other stuff (or nothing at all) as arguments. Sending the button as sender is just a habit.
A developer using your user control can attach a so called "Handler" to implement code as soon as the button was clicked, for example:
AddHandler UserControl1.OnButtonClick, AddressOf OnUserControlButtonClick
This code line should only be executed once, so typically it is placed in the Form_Load event.
Now, in this case the button click is routed to a method called OnUserControlButtonClick() which meets the signature of the event: that means it has one argument which is the sender.
Private Sub OnUserControlButtonClick(ByVal sender as Control)
' custom logic here ...
End Sub
There are so many examples on the web, you could start here.

How to raise event from user control to another form vb.net

I am not familiar with user controls. I have user control with OK and Cancel buttons, I add this user control to an empty form during run time, I have another form which I called "Main Form", In the code I open the empty form and add the user control, after that I want to raise an event (on the OK button) from the user control (or from the empty form I don't know!) to the Main form!
I searched the net and found way to create an event and raise the event in the same form. I tried to do the same thing between different forms but I don't know how to do that.
create event
Public Event OKEvent As EventHandler
raise event
Protected Overridable Sub OnbtnOKClick(e As EventArgs)
AddHandler OKEvent , AddressOf btnOKClickHandler
RaiseEvent OKEvent(Me, e)
End Sub
event Sub
Sub btnOKClickHandler(sender As Object, e As EventArgs)
'Event Handling
'My event code
End Sub
handle my event on btnOK.click event
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
OnbtnOKClick(e)
End Sub
Okey, that all code works in the same form, maybe its messy but that what I found on the net, I want to make similar thing but on different forms, how can I organize my code?
You don't raise an event "to" anywhere. The whole point of events is that you don't have to care who is listening. It's up to the whoever wants to react to the event to handle it and whoever raised the event never has to know about them.
So, all you need to do in this case is have the main form handle the appropriate event(s) of the user control. The user control is a control like any other and the event is an event like any other so the main form handles the event of the user control like it would handle any other event of any other control. Where you create the user control, use an AddHandler statement to register a handler for the event you declared in the user control.
EDIT:
The OnbtnOKClick method that you have shown above should not look like this:
Protected Overridable Sub OnbtnOKClick(e As EventArgs)
AddHandler OKEvent , AddressOf btnOKClickHandler
RaiseEvent OKEvent(Me, e)
End Sub
but rather like this:
Protected Overridable Sub OnbtnOKClick(e As EventArgs)
RaiseEvent OKEvent(Me, e)
End Sub
Also, the btnOKClickHandler method should be in the main form, not the user control. As I said in my answer, it's the main form that handles the event. That means that the event handler is in the main form. As I also said, when you create the user control in the main form, that is where you register the event handler, e.g.
Dim uc As New SomeUserControl
AddHandler uc.OKEvent, AddressOf btnOKClickHandler
As I hope you have absorbed in your reading, if you use AddHandler to register an event handler then you need a corresponding RemoveHandler to unregister it when the object is finished with.
If I'm understanding correctly, you have...
FormA creates FormB.
FormB creates UserControlB.
UserControlB raises "OK" event.
FormB receives "OK" event.
...but you want an additional step of:
FormA receives "OK" event.
The problem here is that FormA has no reference to UserControlB because FormB was the one that created the UserControl. An additional problem is that FormB may have no idea who FormA is (depending on how you've got it setup).
Option 1 - Pass References
If you want both FormB and FormA to respond to a SINGLE "OK" event (generated by the UserControl), then you'd have to somehow have a reference to all three players in the same place so that the event can be properly wired up. The logical place to do this would be in FormB as that is where the UserControl is created. To facilitate that, however, you'd have to modify FormB so that a reference to FormA is somehow passed to it. Then you can wire up the "OK" event directly to the handler in FormA when FormB creates its instance of UserControlB:
Public Class FormA
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frmB As New FormB(Me) ' pass reference to FormA into FormB via "Me" and the Constructor of FormB
frmB.Show()
End Sub
Public Sub ucB_OKEvent()
' ... do something in here ...
Debug.Print("OK Event received in FormA")
End Sub
End Class
Public Class FormB
Private _frmA As FormA
Public Sub New(ByVal frmA As FormA)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_frmA = frmA ' store reference to FormA so we can use it later
End Sub
Private Sub FormB_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ucB As New UserControlB
ucB.Location = New Point(10, 10)
AddHandler ucB.OKEvent, AddressOf _frmA.ucB_OKEvent ' wire up the "OK" event DIRECTLY to the handler in our stored reference of FormA
Me.Controls.Add(ucB)
End Sub
End Class
Public Class UserControlB
Public Event OKEvent()
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
RaiseEvent OKEvent()
End Sub
End Class
Option 2 - "Bubble" the Event
Another option is "bubble" the event from FormB up to FormA. In this scenario, FormB will have no idea who FormA is, so no reference will be passed. Instead, FormB will have its own "OK" event that is raised in response to receiving the original "OK" event from UserControlB. FormA will get the "OK" notification from the UserControl, just not directly:
Public Class FormA
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frmB As New FormB
AddHandler frmB.OKEvent, AddressOf frmB_OKEvent
frmB.Show()
End Sub
Private Sub frmB_OKEvent()
' ... do something in here ...
Debug.Print("OK Event received from FormB in FormA")
End Sub
End Class
Public Class FormB
Public Event OKEvent()
Private Sub FormB_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ucB As New UserControlB
ucB.Location = New Point(10, 10)
AddHandler ucB.OKEvent, AddressOf ucB_OKEvent
Me.Controls.Add(ucB)
End Sub
Private Sub ucB_OKEvent()
Debug.Print("OK Event received from UserControl in FormB")
RaiseEvent OKEvent()
End Sub
End Class
Public Class UserControlB
Public Event OKEvent()
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
RaiseEvent OKEvent()
End Sub
End Class
Design Decisions
You have to make a design decision here. Who is the source of the "OK" event? Should it be the UserControl or FormB? Will the UserControl ever be used in different forms (other than FormB)? Will FormB ever be used with Forms other then FormA? These answers may help you decide which approach is better...or may lead you to rethink how you've designed your current solution; you may need to change it altogether.

How can I find the sender of ContextMenuStrip?

Situation:
I have a context menu in a VB.NET form with fires an event handler on ItemClicked. The auto-generated subroutine receives sender and e as parameters. As I don't reinvent the wheel multiple times, I linked this context menu to three text boxes. Let's name them Textbox1, Textbox2 and Textbox3.
Problem: How can I figure out in which textbox the menu was opened?
Okay, what did I already try?
sender contains the menu itself,
e.ClickedItem just returns the single menu item that was selected.
sender.Parent is always nothing
sender.OwnerItem is also always Nothing`
Me.Textbox1.Focused is always False, even if its the "parent" control of the menu.
Okay, I found a solution that works fine, and here's the code for all VB.NET coders that have the same problem.
The context menu is linked in TextBox1, so we need to add another event handler that saves the sending control into the menu:
Private Sub TextBox1_MouseUp(sender As Windows.Forms.Control, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp
If e.Button = Windows.Forms.MouseButtons.Right Then
ContextMenu.Tag = sender
End If
End Sub
And this is the code of the event handler when clicking a menu item:
Private Sub ContextMenu_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenu.ItemClicked
ContextMenu.Close()
If ContextMenu.Tag Is Nothing Then
Debug.Print("debug info: forgot to set sender? well ... KABOOM!")
Exit Sub
End If
Dim oParent As Windows.Forms.Control
Try
oParent = ContextMenu.Tag
Catch ex As Exception
Debug.Print("debug info: tag contains data other than sender control. well ... KABOOM!")
Exit Sub
End Try
' Do fancy stuff here.
' Release sender
ContextMenu.Tag = Nothing
End Sub
The ContextMenuStrip has a SourceControl property which contains a reference to the control which opened the menu. The event fires from one of the ToolStripMenuItems in the ContextMenuStrip, so you have to get the "parent" first:
' cast sender to menuitem
Dim mi = CType(sender, ToolStripMenuItem)
' cast mi.Owner to CMS
Dim cms = CType(mi.Owner, ContextMenuStrip)
' the control which opened the menu:
Console.WriteLine(cms.SourceControl.Name)
Under certain conditions the SourceControl can get lost but you can track it yourself with a variable and the parent ContextMenuStrip Opening event:
' tracking var:
Private MenuSourceControl As Control
Private Sub cms_Opening(sender As Object, e As CancelEventArgs) Handles cms.Opening
' set reference in case/before it is lost
MenuSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub CutToolStripMenuItem_Click(sender...
If MenuSourceControl IsNot Nothing Then
' do your stuff
' optionally clear the tracking var
MenuSourceControl = Nothing
End If
End Sub
It should be also easier to get the SourceControl when dealing with sub items
You can also capture the related control in the MouseDown event of the related Control in cases where the same menu is used with different controls:
Private Sub lv2_MouseDown(sender As Object,
e As MouseEventArgs) Handles lv2.MouseDown,
myLV.MouseDown, lv1.MouseDown ...
If e.Button = Windows.Forms.MouseButtons.Right Then
MenuSourceControl = DirectCast(sender, Control)
End If
End Sub

How can I change the CheckChanged when clicking the same object in VB 2010?

I want to know if it is possible in VB 2010 to changed the CheckChanged of a CheckBox when clicking the same object. For Example:
I have a 1 picturebox named pic1 and a checkbox named chck1, If I click the pic1, the chck1 must be checked but If I click again the pic1, chck1 must be unchecked and I click again the pic1, chck1 must be check again and so on..
I really don't have an idea if it is working or impossible in VB 2010, I hope someone can help me. Thank you very much.
If it's a WinForm, then you just have to implement something like this:
you have your PictureBox and your Checkbox, and you just have to add a clickhandler to your picturebox like this:
private void pictureBox1_Click(object sender, EventArgs e)
{
checkBox1.Checked = !checkBox1.Checked;
}
This Method always negates the Checked-State of the Checkbox (it's way simpler than a if/else)
checkbox1.Checked contains the checked-state, so that is how you can uncheck/check it.
Edit: i did it in c#, sorry,
in VB.NET it would be something like
Private Sub pictureBox1_Click(sender As Object, e As EventArgs)
checkBox1.Checked = Not checkBox1.Checked;
End Sub
In a WinForms application just add the event handler for the click event of your PictureBox.
You could that easily with the Form Designer or, if using code, then write
' In the form constructor
Public Sub Form1()
' First initialize your form controls'
InitializeComponent()
' then add the event handler for the picturebox click event'
AddHandler pic1.Click, AddressOf pic1_Click
End Sub
Private Sub pic1_Click(sender As Object, e As EventArgs)
' toogle the checked state of the checkbox'
chk1.Checked = Not chk1.Checked
End Sub
As said below from Mr Neolisk you could also shorten this code simply adding the Handles clause to the pic1_Click event thus removing the code in the Form constructor
Private Sub pic1_Click(sender As Object, e As EventArgs) Handles pic1.Click
' toogle the checked state of the checkbox'
chk1.Checked = Not chk1.Checked
End Sub

How can a called form get the caller ID or tag of the calling control

I have a button on my form FormA which is called search. When this button is clicked the frmSearch loads. I want to make the frmSearch dynamic so if it called by the button 'Search Employee' it searches only employees etc.
Is there a way which I can input the caller's ID or tag into frmSearch instantly?
This is what I have at the moment but it only identifies the caller control. (I could instantiate a global variable and read it from frmSearch but I'm wondering if there's a better way):
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
frmSearch.Show()
Dim btn As Button = CType(sender, Button)
MsgBox(btn.ToString)
MsgBox("you have clicked button " & CType(CType(sender, _
System.Windows.Forms.Button).Tag, String))
End Sub
In formA your code will look something like this
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim caller As String = DirectCast(sender, Button).Name
Dim f As New frmSearch(caller)
f.Show()
End Sub
Note that I am not using the default instance of the search form, this is important.
In the search form add this code
Dim whoCalled As String '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Public Sub New(caller As String)
InitializeComponent()
whoCalled = caller
End Sub
The variable whoCalled will contain the name of the caller.
If you want to make it impossible to create the form without passing the data, then in the search form also add
Private Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
This will force you to use the overloaded constructor.