0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# DataGridView マウスホイールで左右スクロールする

Last updated at Posted at 2023-10-15

ソースコード

  • ホイール操作:上下スクロール(通常通り)
  • マウスの右ボタンを押しながらホイール操作:左右スクロール
//ホイール操作で上下スクロール、マウスの右ボタンを押しながらホイール操作で左右スクロール
dataGridView1.MouseWheel += (sender, e) =>
{
    DataGridView dataGridView = sender as DataGridView;

    //マウスの右ボタンが押されている場合は左右スクロール
    if ((MouseButtons & MouseButtons.Right) == MouseButtons.Right)//この1行をなくすと通常のホイール操作が左右スクロールに置き換わる
    {
        //スクロール列数
        int scrollNum = 3;

        //ホイール手前で右へ移動
        bool right = e.Delta < 0;

        //「表示される最初の列」が列固定などで画面外にある場合は処理しない
        if (dataGridView.FirstDisplayedScrollingColumnIndex >= 0)
        {
            int nextIndex, preCheckIndex;

            nextIndex = preCheckIndex = dataGridView.FirstDisplayedScrollingColumnIndex;

            //所定列分スクロールする
            for (int counter = 0; counter < scrollNum;)
            {
                preCheckIndex += right ? 1 : -1;

                //インデックスが範囲外、または固定列の場合は終了
                if (preCheckIndex < 0 || dataGridView.ColumnCount - 1 < preCheckIndex || dataGridView.Columns[preCheckIndex].Frozen)
                {
                    break;
                }

                //非表示セルの場合はカウントしない
                if (dataGridView.Columns[preCheckIndex].Visible)
                {
                    counter++;
                    nextIndex = preCheckIndex;
                }
            }

            //「表示される最初の列」を更新
            dataGridView.FirstDisplayedScrollingColumnIndex = nextIndex;

            //最左端のセルの場合で、セルが部分的に隠れている場合はオフセットを0にして隠れている部分をなくす
            if (!right && dataGridView.FirstDisplayedScrollingColumnHiddenWidth == dataGridView.HorizontalScrollingOffset)
            {
                dataGridView.HorizontalScrollingOffset = 0;
            }
        }

        //処理完了
        ((HandledMouseEventArgs)e).Handled = true;
    }
};

参考URL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?