简体   繁体   English

如何获得一个DataGridView行作为光标图标的位图?

[英]How to get a DataGridView Row as Bitmap for a cursor icon?

I'm trying to get a DataGridViews row as Bitmap to use it as a cursors icon. 我正在尝试将DataGridViews行作为Bitmap用作光标图标。 Sadly the DataGridViewRow object has no DrawToBitmap method. 遗憾的是,DataGridViewRow对象没有DrawToBitmap方法。

I managed to get the bound of the row (RowRect) and get a Bitmap of the whole DataGridView (bmp). 我设法获得行的边界(RowRect),并获得整个DataGridView(bmp)的位图。 I think I next need to cut the row from the bitmap, but I have no idea how to do that. 我想我接下来需要从位图中删除行,但是我不知道该怎么做。

Here is my starting code: 这是我的起始代码:

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

You need to grab the whole clientarea content first (your bitmap is too small!), then cut out the row rectangle. 您需要先获取整个工作区的内容(您的位图太小!),然后切出行矩形。 Also make sure to dispose of the created resources! 另外,请确保处置创建的资源!

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM