C# Windows 窗体触发 Keypess

发布于 2024-12-11 17:10:42 字数 7491 浏览 1 评论 0原文

我试图让“取消”按钮事件在用户按下表单上任意位置的 Escape 键时触发。

我已经尝试了几种方法,但表单的 Keypress 事件只是不想触发

我的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CLT
{
    public partial class UnallocatedReceipts : UserControl
    {
        #region Windows Forms Designer


        private void InitializeComponent()
        {
        }

        #endregion

        //Constructor that Initializes the Form
        public UnallocatedReceipts()
        {
            InitializeComponent();
        }

        BLLService ws = new BLLService();

        //Set the properties and Datasets used in the form
        DataSet banks = new DataSet();

        public String ClientName { get; set; }
        public Int32 CompanyCode { get; set; }
        public Int32 UserLevel { get; set; }
        public Int32 BranchCode { get; set; }
        public Int32 UserCode { get; set; }


        private void UnallocatedReceipts_Load(object sender, EventArgs e)
        {
            txtClientNumber.Focus();
        }


        //Populates the Client Info Grid
        private void PopulateGrid(Int32 clientNumber)
        {
            datPortfolio.DataSource = ws.PortfolioSearch(clientNumber.ToString(), CompanyCode, UserLevel, BranchCode).Tables[0];
        }

        //Gets the Client information and sets the Client Name Label to the selected client
        private void GetClientInfo()
        {
            DataRow dr = ws.GetClient(txtClientNumber.Text, 0, 9).Tables[0].Rows[0];
            lblClientName.Text = dr["g"].ToString() + " " + dr["f"].ToString();
            lblClientName.Visible = true;
            lblCltName.Visible = true;
        }

        /*Method that runs when the search button is clicked, method calls Validate Client Number that checks 
        if the Client Number that was entered is a valid number*/
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            datPortfolio.DataSource = null;

            if (ValidClientNumber())
            {
                Cursor.Current = Cursors.WaitCursor;

                GetClientInfo();
                PopulateGrid(Convert.ToInt32(txtClientNumber.Text));
                //ClientExisting nc = new ClientExisting(ClientName, LoadClient, EnterFromBusiness);
                datPortfolio.Focus(); 
            }            
        }


        //Retrieves the Bank Name and Bank Code
        private void GetBanks()
        {
            banks = ws.QBankGroupsForBD();

            DataView dvBank = new DataView(banks.Tables[0]);
            cboBankAccount.DataSource = dvBank;
            cboBankAccount.ValueMember = banks.Tables[0].Columns[0].ColumnName;
            cboBankAccount.DisplayMember = banks.Tables[0].Columns[1].ColumnName;
            cboBankAccount.Enabled = true;
        }

        //Method to clear the form when Cancel button is clicked and also when Receipt has been inserted
        private void ClearForm()
        {
            txtClientNumber.Text = "";
            lblClientName.Visible = false;
            lblCltName.Visible = false;
            lblCltName.Text = "";
            datPortfolio.DataSource = null;
            txtAccountNumber.Text = "";
            txtAccountNumber.ReadOnly = true;
            dtpActionDate.Enabled = false;
            dtpActionDate.Value = DateTime.Today;
            txtDescription.Text = "";
            txtDescription.ReadOnly = true;
            txtAmount.Text = "";
            txtAmount.ReadOnly = true;
            cboBankAccount.DataSource = null;
            cboBankAccount.Enabled = false;
            ActionDate = DateTime.Today;
        }


        //Method that validates the entries that was made in the form when the save button is clicked
        private bool ValidateEntries()
        {
            decimal value;
            bool isDecimal = decimal.TryParse(txtAmount.Text, out value);

            if (ActionDate > DateTime.Today)
            {
                MessageBox.Show("Action Date must be today or in the past");
                dtpActionDate.Focus();
                return false;
            }
            else if(txtDescription.Text == "")
            {
                MessageBox.Show("Please complete the Description");
                txtDescription.Focus();
                return false;
            }
            else if (isDecimal == false)
            {
                MessageBox.Show("Please enter a valid decimal");
                txtAmount.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

        //Method that calls the store proc to insert the Receipts in the Database
        private void InsertUnAllocatedReceipts()
        {

            try
            {
                ws.InsertUnAllocatedReceipts(
                    int.Parse(txtClientNumber.Text),
                    int.Parse(txtAccountNumber.Text),
                    ActionDate,
                    txtDescription.Text,
                    decimal.Parse(txtAmount.Text),
                    Convert.ToInt32(UserCode),
                    int.Parse(cboBankAccount.SelectedValue.ToString())
                    );
            }
            catch (Exception ex)
            {
                 MessageBox.Show("Please contact your System Administrator!\n\nDetailed error follows: " + ex.ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void datPortfolio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter) //If enter is pressed
            {
                LoadReceiptInformation();
            }
        }

        //Loads the Receipt information that needs to be completed in order to save the receipt
        private void LoadReceiptInformation()
        {
            txtAccountNumber.Text = datPortfolio[datPortfolio.CurrentRowIndex, 2].ToString();
            dtpActionDate.Enabled = true;
            txtAmount.Enabled = true;
            txtDescription.Enabled = true;
            GetBanks();
            dtpActionDate.Focus();
        }

        private void datPortfolio_DoubleClick(object sender, EventArgs e)
        {
            LoadReceiptInformation();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateEntries())
            {
                InsertUnAllocatedReceipts();
                MessageBox.Show("Your Unallocated Receipt has been Inserted");
                ClearForm();
            }
        }

        //Fires the Search client click event that loads the datagrid when enter is pressed
        private void txtClientNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch.PerformClick();
                e.Handled = true;
            }
        }



        private void cboBankAccount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnSave.PerformClick();
                e.Handled = true;
            }
        }


    }
}

如果有人可以帮助我,我将不胜感激

I am trying to get the Cancel button event to fire whenever the user presses the Escape key anywhere on the form.

I have tried several methods but the Keypress event for the form just does not want to fire

My code is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CLT
{
    public partial class UnallocatedReceipts : UserControl
    {
        #region Windows Forms Designer


        private void InitializeComponent()
        {
        }

        #endregion

        //Constructor that Initializes the Form
        public UnallocatedReceipts()
        {
            InitializeComponent();
        }

        BLLService ws = new BLLService();

        //Set the properties and Datasets used in the form
        DataSet banks = new DataSet();

        public String ClientName { get; set; }
        public Int32 CompanyCode { get; set; }
        public Int32 UserLevel { get; set; }
        public Int32 BranchCode { get; set; }
        public Int32 UserCode { get; set; }


        private void UnallocatedReceipts_Load(object sender, EventArgs e)
        {
            txtClientNumber.Focus();
        }


        //Populates the Client Info Grid
        private void PopulateGrid(Int32 clientNumber)
        {
            datPortfolio.DataSource = ws.PortfolioSearch(clientNumber.ToString(), CompanyCode, UserLevel, BranchCode).Tables[0];
        }

        //Gets the Client information and sets the Client Name Label to the selected client
        private void GetClientInfo()
        {
            DataRow dr = ws.GetClient(txtClientNumber.Text, 0, 9).Tables[0].Rows[0];
            lblClientName.Text = dr["g"].ToString() + " " + dr["f"].ToString();
            lblClientName.Visible = true;
            lblCltName.Visible = true;
        }

        /*Method that runs when the search button is clicked, method calls Validate Client Number that checks 
        if the Client Number that was entered is a valid number*/
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            datPortfolio.DataSource = null;

            if (ValidClientNumber())
            {
                Cursor.Current = Cursors.WaitCursor;

                GetClientInfo();
                PopulateGrid(Convert.ToInt32(txtClientNumber.Text));
                //ClientExisting nc = new ClientExisting(ClientName, LoadClient, EnterFromBusiness);
                datPortfolio.Focus(); 
            }            
        }


        //Retrieves the Bank Name and Bank Code
        private void GetBanks()
        {
            banks = ws.QBankGroupsForBD();

            DataView dvBank = new DataView(banks.Tables[0]);
            cboBankAccount.DataSource = dvBank;
            cboBankAccount.ValueMember = banks.Tables[0].Columns[0].ColumnName;
            cboBankAccount.DisplayMember = banks.Tables[0].Columns[1].ColumnName;
            cboBankAccount.Enabled = true;
        }

        //Method to clear the form when Cancel button is clicked and also when Receipt has been inserted
        private void ClearForm()
        {
            txtClientNumber.Text = "";
            lblClientName.Visible = false;
            lblCltName.Visible = false;
            lblCltName.Text = "";
            datPortfolio.DataSource = null;
            txtAccountNumber.Text = "";
            txtAccountNumber.ReadOnly = true;
            dtpActionDate.Enabled = false;
            dtpActionDate.Value = DateTime.Today;
            txtDescription.Text = "";
            txtDescription.ReadOnly = true;
            txtAmount.Text = "";
            txtAmount.ReadOnly = true;
            cboBankAccount.DataSource = null;
            cboBankAccount.Enabled = false;
            ActionDate = DateTime.Today;
        }


        //Method that validates the entries that was made in the form when the save button is clicked
        private bool ValidateEntries()
        {
            decimal value;
            bool isDecimal = decimal.TryParse(txtAmount.Text, out value);

            if (ActionDate > DateTime.Today)
            {
                MessageBox.Show("Action Date must be today or in the past");
                dtpActionDate.Focus();
                return false;
            }
            else if(txtDescription.Text == "")
            {
                MessageBox.Show("Please complete the Description");
                txtDescription.Focus();
                return false;
            }
            else if (isDecimal == false)
            {
                MessageBox.Show("Please enter a valid decimal");
                txtAmount.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

        //Method that calls the store proc to insert the Receipts in the Database
        private void InsertUnAllocatedReceipts()
        {

            try
            {
                ws.InsertUnAllocatedReceipts(
                    int.Parse(txtClientNumber.Text),
                    int.Parse(txtAccountNumber.Text),
                    ActionDate,
                    txtDescription.Text,
                    decimal.Parse(txtAmount.Text),
                    Convert.ToInt32(UserCode),
                    int.Parse(cboBankAccount.SelectedValue.ToString())
                    );
            }
            catch (Exception ex)
            {
                 MessageBox.Show("Please contact your System Administrator!\n\nDetailed error follows: " + ex.ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void datPortfolio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter) //If enter is pressed
            {
                LoadReceiptInformation();
            }
        }

        //Loads the Receipt information that needs to be completed in order to save the receipt
        private void LoadReceiptInformation()
        {
            txtAccountNumber.Text = datPortfolio[datPortfolio.CurrentRowIndex, 2].ToString();
            dtpActionDate.Enabled = true;
            txtAmount.Enabled = true;
            txtDescription.Enabled = true;
            GetBanks();
            dtpActionDate.Focus();
        }

        private void datPortfolio_DoubleClick(object sender, EventArgs e)
        {
            LoadReceiptInformation();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateEntries())
            {
                InsertUnAllocatedReceipts();
                MessageBox.Show("Your Unallocated Receipt has been Inserted");
                ClearForm();
            }
        }

        //Fires the Search client click event that loads the datagrid when enter is pressed
        private void txtClientNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch.PerformClick();
                e.Handled = true;
            }
        }



        private void cboBankAccount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnSave.PerformClick();
                e.Handled = true;
            }
        }


    }
}

I would it appreciate it if someone can assist me

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

神经暖 2024-12-18 17:10:42

重写 ProcessCmdKey 以处理用户控件中的按键事件:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // 0x100 is WM_KEYDOWN
    if (msg.Msg == 0x100 && keyData == Keys.Escape)
    {
        //
        // call your cancel method here
        //

        // return true if you have handled the key press
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Override ProcessCmdKey to handle key events in a user control:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // 0x100 is WM_KEYDOWN
    if (msg.Msg == 0x100 && keyData == Keys.Escape)
    {
        //
        // call your cancel method here
        //

        // return true if you have handled the key press
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
俯瞰星空 2024-12-18 17:10:42
this.CancelButton = btnCancel;

其中 btnCancel 是您的取消按钮。

this.CancelButton = btnCancel;

where btnCancel is your cancel button.

若能看破又如何 2024-12-18 17:10:42

设置 Form.KeyPreview=true 并处理 KeyDown 事件或设置 CancelButton=ButtonID

Set Form.KeyPreview=true and handle the KeyDown event or set CancelButton=ButtonID.

流殇 2024-12-18 17:10:42
private void MyForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if((Keys) e.KeyValue == Keys.Escape) 
        //this.Close(); or whatever your cancel action
}

并将 KeyPreview 设置为 true

private void MyForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if((Keys) e.KeyValue == Keys.Escape) 
        //this.Close(); or whatever your cancel action
}

and set KeyPreview to true

沧桑㈠ 2024-12-18 17:10:42

如果您按下某些系统键,则不会触发 KeyPress 事件。使用 KeyDown 代替:

private void myControl_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            btnSave.PerformClick();
            e.Handled = true;
        }
    }

KeyPress event don't fire if you press some system keys. Use KeyDown instead:

private void myControl_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            btnSave.PerformClick();
            e.Handled = true;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文