Other Recent Articles

Raising a Button Click event programmatically

By Eranda Ketawalage on Wednesday, July 4, 2012 0 comments



When developing windows (C#) forms, as developers we are very much concerning about speedup data entering of users. Minimizing use of mouse, use of tab key to move courser from one text box to another, etc. are main methods can increase data entering speed.
Other than that use shortcut key for button operations is also speed up the data entering.
As an example thinks that we can assign F2 key for data saving and F3 for deleting addition to having Save and Delete buttons.

According to our common practice we are write the code to save the record under button click event of “Save” button.

private void btnSave_Click(object sender, EventArgs e)
{
//The code goes here
}

private void btnEdit_Click(object sender, EventArgs e)
{
//The code goes here
}


To execute same method for F2 key press event, we have to override inherited method of the form which called ProcessDialogKey.



Parameters
keyData
One of the Keys values that represents the key to process.
Return Value
true if the key was processed by the control; otherwise, false.
Remarks
This method is called during message preprocessing to handle dialog characters, such as TAB, RETURN, ESCAPE, and arrow keys. This method is called only if the IsInputKey method indicates that the control is not processing the key. The ProcessDialogKey simply sends the character to the parent'sProcessDialogKey method, or returns false if the control has no parent. TheForm class overrides this method to perform actual processing of dialog keys. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control. (Source)





protected override bool ProcessDialogKey(Keys keyData)
{
//The code goes here
}

To call the Click event of save button we have to call PerformClick method of it like btnSave.PerformClick().


protected override bool ProcessDialogKey(Keys keyData)
{
     if (keyData == Keys.F2)
     {
         btnSave.PerformClick();
         return true;
     }
     else if (keyData == Keys.F4)
     {
         btnEdit.PerformClick();
         return true;
     }
     else
     {
         return base.ProcessDialogKey(keyData);
     }
}


Category: C# , Visual Studio , VS2010 , Windows Form

0 comments:

Post a Comment

Amazon

Share this