0

Windowsフォームコントロールを拡張して、そのオブジェクトの各インスタンスのキープレスイベントを処理するイベントハンドラーを常に持つようにする継承クラスを作成する方法を理解するのに少し問題があります。

私はおそらくこれをうまく説明していません。基本的に、WindowsフォームのDatagridViewクラスを拡張して、拡張されたDatagridViewクラスのインスタンス化されたオブジェクトに常にkeyPressイベントハンドラーが存在するようにします。

キーの押下をリッスンし、以下に記述したものと同様のコードでそれらを処理するイベントハンドラーを使用できるかどうか疑問に思いました。

    private void dgvObject_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetterOrDigit(e.KeyChar))
        {
            //start the loop at the currently selected row in the datagridview
            for (int i = dgvObject.SelectedRows[0].Index; i < dgvObject.Rows.Count; i++)
            {
                //will only evaluate to true when the current index has iterated above above the 
                //selected rows index number AND the key press event argument matches the first character of the current row
                // character of the 
                if (i > dgvObject.SelectedRows[0].Index && dgvObject.Rows[i].Cells[1].FormattedValue
                    .ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
                {
                    //selects current iteration as the selected row
                    dgvObject.Rows[i].Selected = true;
                    //scrolls datagridview to selected row
                    dgvObject.FirstDisplayedScrollingRowIndex = dgvObject.SelectedRows[0].Index;
                    //break out of loop as I want to select the first result that matches
                    break;
                }
            }
        }
    }

上記のコードは、起動時にkeypressイベントのイベント引数にあるものの文字で始まる次の行を選択するだけです。これを常に存在する継承されたハンドラーとして使用できるかどうか疑問に思った理由。個々のDatagridViewオブジェクトごとに、Windowsフォームで数百のハンドラーを明示的に作成するよりも優れていると思いました。私の考えが間違っている場合は、遠慮なく私を訂正してください!とにかく入力してくれてありがとう。

私はC#でプログラミングを始めて約5か月になりますが、それでも学習を続けています=)

4

2 に答える 2

3

はい、継承されたクラスではオーバーライドするだけです。後でOnKeyPress呼び出すことを忘れないでください。base.OnKeyPress

protected override OnKeyPress(KeyPressEventArgs e)
{
   .. all your code

   base.OnKeyPress(e); // to ensure external event handlers are called
}
于 2012-12-17T11:32:04.397 に答える
1

ProcessCmdKeyをオーバーライドすることで、すべてのキーの押下と組み合わせさえもキャッチできます。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    if (keyData == (Keys.Control | Keys.F)) 
    {
        //your code here
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
于 2012-12-17T11:35:29.663 に答える