H.Tran
H.Tran

Reputation: 41

Detect Mouse Over on Image inside DatagridviewCell

I created a custom DataGridView column which hosts both an image and text by deriving from the DataGridViewTextBoxCell class.

I would like to be able to detect when the mouse cursor is over only the image portion of the cell.

https://i.sstatic.net/hfMHw.jpg

I tried creating a Rectangle object for each cell which gets set to the boundaries of the image in the Paint() method and determining whether the cursor location is contained in the boundary rectangle in the OnMouseMove() handler but this didn't work.

  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";
        }
    }

Upvotes: 2

Views: 337

Answers (1)

TaW
TaW

Reputation: 54433

This doesn't answer your question but as it works for a DataGridViewImageCell I decided to leave it as a reference.

Your code looks pretty similar. Make sure to keep the Location of the imgBoundsRect at (0,0) just like the mouse coordinates in the CellMouseMove!

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";
    }
}

Upvotes: 1

Related Questions