// dgvrightclick.cs using System; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; public class MyForm : Form { DataGridView dgv; // フォームのLoadイベント・ハンドラ void MyForm_Load(object sender, EventArgs e) { // データソースとして画像デコーダ一覧を使用 dgv.DataSource = ImageCodecInfo.GetImageDecoders(); } // DataGridViewのCellMouseClickイベント・ハンドラ void dgv_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { // 右ボタンのクリックか? if (e.Button == MouseButtons.Right) { // ヘッダ以外のセルか? if (e.ColumnIndex >= 0 && e.RowIndex >= 0) { // 右クリックされたセル DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex]; // セルの選択状態を反転 cell.Selected = !cell.Selected; } } } // フォームのコンストラクタ public MyForm() { dgv = new DataGridView(); dgv.Dock = DockStyle.Fill; dgv.CellMouseClick += new DataGridViewCellMouseEventHandler(dgv_CellMouseClick); this.Controls.Add(dgv); this.Size = new Size(480, 240); this.Load += new EventHandler(MyForm_Load); } } class Program { [STAThread] static void Main() { Application.Run(new MyForm()); } } // コンパイル方法:csc dgvrightclick.cs