MOUSE POSITION
I am trying to get the exact position of the mouse when it enters a cell. I know I get the cell.virtual bounds but this does not always seem to equate to the top left hand corner of the cell which I thought it would. What I am trying to do is show a windows LABEL at the top right of the cell that I just entered – how can I do that?
Also I want to display a similar label when the mouse enters a column header but there are no events that seem to be fired to capture when the mouse is over the column header – can this be done?
Thanks
-
Dear Hamish,
The best way to do it - is to draw labels in Grid.PaintCell & Grid.PaintColumnCaption routines. You should also invalidate cells when you enter/leave them. Please find an example demonstrating the wanted behavior:
public partial class DapforDemo : Form
{
readonly Font _font = new Font("Arial", 6, FontStyle.Italic|FontStyle.Bold);
public DapforDemo()
{
InitializeComponent();
//Populate the grid here...
//Invalidate cells when the mouse enters or leaves them
grid.CellEnter += delegate(object sender, GridCellEventArgs e) { e.Cell.Invalidate(); };
grid.CellLeave += delegate(object sender, GridCellEventArgs e) { e.Cell.Invalidate(); };
//Cell painting routine
grid.PaintCell += delegate(object sender, PaintCellEventArgs e)
{
//Do default painting
e.PaintAll();
e.Handled = true;
//Draw a custom label in the top-right corner of cell
if (e.Cell.Column != null && e.Cell.VirtualBounds.Contains(grid.PointToClient(MousePosition)))
{
string label = string.Format("cell {0},{1}",e.Cell.Row.VisibleIndex,e.Cell.Column.VisibleIndex);
using(StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Far;
sf.LineAlignment = StringAlignment.Near;
e.Graphics.DrawString(label, _font, Brushes.Red, e.Cell.VirtualBounds, sf);
}
}
};
//Column painting routine
grid.PaintColumnCaption += delegate(object sender, PaintColumnCaptionEventArgs e)
{
//Do default painting
e.PaintAll();
e.Handled = true;
//Draw a custom label
if (e.Column != null && e.VirtualBounds.Contains(grid.PointToClient(MousePosition)))
{
string label = string.Format("column {0}", e.Column.VisibleIndex);
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Far;
sf.LineAlignment = StringAlignment.Near;
e.Graphics.DrawString(label, _font, Brushes.Red, e.VirtualBounds, sf);
}
}
};
}
}Best regards,
Dapfor
0
Please sign in to leave a comment.
Comments
1 comment