項目を右クリックでも選択できるようにする

ListBoxで、項目を右クリックでも選択できるようにするには
自分でマウスイベントを捕捉して
マウスポインター位置より選択すべきアイテムのインデックスを取得し
そのアイテムを選択させます。
他にも方法はあると思いますが参考程度に

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 適当に項目を追加
            for(int i = 0; i < 100; i++)
            {
                listBox1.Items.Add(i.ToString());
            }

            // マウスボタンが離されたイベント取得
            listBox1.MouseUp += new MouseEventHandler(listBox1_MouseUp);
        }

        void listBox1_MouseUp(object sender, MouseEventArgs e)
        {
            // 右クリックされた?
            if(e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                // マウス座標から選択すべきアイテムのインデックスを取得
                int index = listBox1.IndexFromPoint(e.Location);

                // インデックスが取得できたら
                if(index >= 0)
                {
                    // すべての選択状態を解除してから
                    listBox1.ClearSelected();

                    // アイテムを選択
                    listBox1.SelectedIndex = index;
                }
            }
        }
    }
}

なお、コンテキストメニューを割り当てている場合は
マウスクリックのイベントそのものが発生しなかったりしますが
その場合も
自分でコンテキストメニューをハンドラ内で表示させるなどしてください。

    // インデックスが取得できたら
    if(index >= 0)
    {
        // すべての選択状態を解除してから
        listBox1.ClearSelected();

        // アイテムを選択
        listBox1.SelectedIndex = index;

        // コンテキストメニューを表示
        Point pos = listBox1.PointToScreen(e.Location);
        contextMenuStrip1.Show(pos);
    }

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)