C# 跨越ListView的滚动条截图
[原文链接: http://blog.csdn.net/zgke/article/details/3836712]
因对ListView控件的打印需求,借鉴了原文的思想得以实现,在此向原文作者表示感谢!
1. 通过Control.DrawToBitmap()方法对ListView的当前显示状态截图,存储于PictureBox中
2. 把PictureBox覆盖到ListView上
3. 通过ListView.GetItemRect(ListView.Items.Count - 1, ItemBoundsPortion.Entire)
获取扩展后不带滚动条的ListViewItem的高度和宽度
4. 根据最后一条ListViewItem的信息重新计算整个ListView的尺寸(应包括绘制到位图后的滚动条信息)
5. 再次通过Control.DrawToBitmap()方法获取ListView的全部形(绘制时应排除灰色滚动条信息)
1 /// <summary> 2 /// ListView跨越滚动截图 3 /// </summary> 4 /// <param name="listView">ListView</param> 5 /// <returns>图形</returns> 6 public static Image GetListViewImage(ListView listView) 7 { 8 PictureBox pic = new PictureBox(); 9 pic.Size = listView.Size; 10 pic.Location = listView.Location; 11 Bitmap bmpPre = new Bitmap(pic.Width, pic.Height); 12 listView.DrawToBitmap(bmpPre, new Rectangle(0, 0, pic.Width, pic.Height)); 13 pic.Image = bmpPre; 14 listView.Parent.Controls.Add(pic); 15 16 listView.Visible = false; 17 Size sizePre = listView.Size; 18 19 // 获取扩展后 * 无滚动条 * 情况下第一条ListViewItem的边框信息 20 // (当前滚动位置相对于ListView的左侧位置、顶部位置、完全显示的宽度、ListViewItem的高度,不包括滚动条信息) 21 Rectangle rectFirst = listView.GetItemRect(0, ItemBoundsPortion.Entire); 22 23 // 获取扩展后 * 无滚动条 * 情况下最后一条ListViewItem的边框信息 24 // (当前滚动位置相对于ListView的左侧位置、顶部位置、完全显示的宽度、ListViewItem的高度,不包括滚动条信息) 25 Rectangle rectLast = listView.GetItemRect(listView.Items.Count - 1, ItemBoundsPortion.Entire); 26 27 // 计算最后一条ListViewItem的边框信息 28 // (如果ListView出现滚动条且滚动位置不在(0,0),则需要手动计算最后一条ListViewItem的边框信息(列标头高度约为20) 29 Rectangle rect = new Rectangle(0, Math.Abs(rectFirst.Y) + Math.Abs(rectLast.Y) + 20, rectLast.Width, rectLast.Height); 30 31 // 每条ListViewItem的宽度加 4 (留出右侧灰色滚动条的位置,绘制到位图时会出现灰色滚动条) 32 int width = rect.Width + rect.X + (listView.Columns.Count * 4); 33 if (width > listView.Width) listView.Width = width; 34 35 // 每条ListViewItem的高度加 3 (留出下侧灰色滚动条的位置,绘制到位图时会出现灰色滚动条) 36 int height = rect.Height + rect.Y + (listView.Items.Count * 3); 37 if (height > listView.Height) listView.Height = height; 38 39 // 重绘控件以正确绘制到位图 40 listView.Refresh(); 41 42 // 绘制ListView到位图(不绘制灰色滚动条) 43 Bitmap bmpNew = new Bitmap(width - (listView.Columns.Count * 3), height - (listView.Items.Count * 2)); 44 listView.DrawToBitmap(bmpNew, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height)); 45 46 listView.Size = sizePre; 47 listView.Visible = true; 48 listView.Parent.Controls.Remove(pic); 49 bmpPre.Dispose(); 50 pic.Dispose(); 51 52 return bmpNew; 53 }

浙公网安备 33010602011771号