2017-07-13 3 views
1

DataGridViewTextBoxCellクラスから派生してイメージとテキストの両方をホストするカスタムDataGridView列を作成しました。DatagridviewCell内の画像上にマウスオーバーを検出

私は、マウスカーソルがセルのイメージ部分だけにあるときを検出できるようにしたいと考えています。

https://i.stack.imgur.com/hfMHw.jpg

I)はpaint()メソッド内の画像の境界に設定されます各セルのRectangleオブジェクトを作成し、カーソル位置がONMOUSEMOVE(内境界矩形に含まれているかどうかを決定しようとしましたハンドラが動作しませんでした。

protected override void Paint(Graphics graphics, Rectangle clipBounds, 
     Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, 
     object value, object formattedValue, string errorText, 
     DataGridViewCellStyle cellStyle, 
     DataGridViewAdvancedBorderStyle advancedBorderStyle, 
     DataGridViewPaintParts paintParts) 
    { 
     // Paint the base content 
     base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, 
      value, formattedValue, errorText, cellStyle, 
      advancedBorderStyle, paintParts); 

     if (this.Image != null) 
     { 
      imgBoundsRect = new Rectangle(cellBounds.Location, this.Image.Size); 
      // Draw the image clipped to the cell. 
      System.Drawing.Drawing2D.GraphicsContainer container = graphics.BeginContainer(); 

      graphics.SetClip(cellBounds); 
      graphics.DrawImageUnscaled(this.Image, cellBounds); 

      graphics.EndContainer(container); 
     } 
    } 

    protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) 
    { 
     base.OnMouseMove(e); 
     Console.WriteLine(e.Location); 
     if (imgBoundsRect.Contains(e.Location)) 
     { 
      this.ToolTipText = "View Doc"; 
     } 
    } 

答えて

0

これは、あなたの質問に答えていませんが、それはDataGridViewImageCellのために働くように私はリファレンスとしてそれを残すことにしました。

コードはかなり似ています。 CellMouseMoveのマウス座標のように、LocationimgBoundsRect(0,0)にしてください。

private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e) 
{ 
    if (e.ColumnIndex < 0 || e.RowIndex < 0) return; 
    DataGridViewImageCell iCell = 
        dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewImageCell; 

    Text = "MISS"; 
    if (iCell != null) 
    { 
     Image img = iCell.FormattedValue as Image; 
     Rectangle irect = new Rectangle(0, 0, img.Width, img.Height); 
     Point relLoc = e.Location; 
     if (irect.Contains(relLoc)) Text = "HIT"; 
    } 
} 
+0

ありがとうございました。私は作業中のプログラムにこれを組み込もうとしましたが、セルに画像とテキストの両方が含まれており、DataGridViewTextBoxCellから派生しているので、カーソルが置かれているセルのテキスト部分か画像部分かを判断できません。 –

+0

はい、わかりました。しかし、それはあなたがやっていることですよね?問題は:矩形 'imgBoundsRect'は正しいですか? – TaW

+0

私は鉱山とあなたのアイデアの両方を使用するソリューションを実装しましたが、現在は機能しています。 rect座標を0、0に設定し、そのrect.containsコードをカスタムクラスのOnMouseMoveイベントハンドラに移動するという提案を使用しました。ありがとう! –

関連する問題