如何获取DataGridView行作为光标图标的位图
本文关键字:光标 图标 位图 DataGridView 何获取 获取 | 更新日期: 2023-09-27 17:59:30
我正在尝试将DataGridViews行作为位图,以将其用作光标图标。遗憾的是,DataGridViewRow对象没有DrawToBitmap方法。
我设法获得了行的边界(RowRect),并获得了整个DataGridView的位图(bmp)。我想我下一步需要从位图中剪切行,但我不知道如何做到这一点。
这是我的起始代码:
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
if (e.Button == MouseButtons.Left)
{
rw = dataGridView1.SelectedRows[0];
Rectangle RowRect = dataGridView1.GetRowDisplayRectangle(rw.Index, true);
Bitmap bmp = new Bitmap(RowRect.Width, RowRect.Height);
dataGridView1.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
Cursor cur = new Cursor(bmp.GetHicon());
Cursor.Current = cur;
rowIndexFromMouseDown = dataGridView1.SelectedRows[0].Index;
dataGridView1.DoDragDrop(rw, DragDropEffects.Move);
}
}
}
您需要首先获取整个客户端区域内容(位图太小!),然后剪切出行矩形。还要确保处理创建的资源!
这应该有效:
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
if (e.Button == MouseButtons.Left)
{
Size dgvSz = dataGridView1.ClientSize;
int rw = dataGridView1.SelectedRows[0].Index;
Rectangle RowRect = dataGridView1.GetRowDisplayRectangle(rw, true);
using (Bitmap bmpDgv = new Bitmap(dgvSz.Width, dgvSz.Height))
using (Bitmap bmpRow = new Bitmap(RowRect.Width, RowRect.Height))
{
dataGridView1.DrawToBitmap(bmpDgv , new Rectangle(Point.Empty, dgvSz));
using ( Graphics G = Graphics.FromImage(bmpRow ))
G.DrawImage(bmpDgv , new Rectangle(Point.Empty,
RowRect.Size), RowRect, GraphicsUnit.Pixel);
Cursor.Current.Dispose(); // not quite sure if this is needed
Cursor cur = new Cursor(bmpRow .GetHicon());
Cursor.Current = cur;
rowIndexFromMouseDown = dataGridView1.SelectedRows[0].Index;
dataGridView1.DoDragDrop(rw, DragDropEffects.Move);
}
}
}
}