C# 从面板上截图

C# 从面板上截图,c#,winforms,C#,Winforms,我试图从一个面板上截取一个屏幕截图,在上面画一些水平线。 我使用了以下代码: private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //hide close button pictureBox1.Visible = false; //Take screenshoot for the DPanel. Bitmap dend = new Bitma

我试图从一个面板上截取一个屏幕截图,在上面画一些水平线。

我使用了以下代码:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //hide close button
    pictureBox1.Visible = false;

    //Take screenshoot for the DPanel.
    Bitmap dend = new Bitmap(dPanel.Width, dPanel.Height);
    Graphics G = Graphics.FromImage(dend);
    System.Drawing.Rectangle rectangle = dPanel.RectangleToScreen(dPanel.ClientRectangle);
    G.CopyFromScreen(rectangle.Location, System.Drawing.Point.Empty, dPanel.Size);
    SomeGlobalVariables.Mygraph = dend;

    Reporttoprint r = new Reporttoprint();
    r.Show();
}
单击linkLabel1时发生异常

似乎当我点击linkLabel1执行代码并从我的面板拍摄时,会再次调用dPanel_Paint action,然后触发异常

这一地区的例外情况:

private void dPanel_Paint(object sender, PaintEventArgs e)
{
    if (k==0)
    {
        //add the "Group" center point to the dictionary.
        ClusterPoint=new Point(((ep1.X+ep2.X)/2),((ep1.Y+ep2.Y)/2));
        //Exception is done here
        clusterpoints.Add(Clusterchar[k], ClusterPoint);
    }
}
有什么帮助吗

提前感谢。

首先,喷漆事件非常频繁地发生(取决于具体情况)

问题是您有重复的密钥。两种解决方案

覆盖现有密钥/值对:

clusterpoints[Clusterchar[k]] = ClusterPoint;
或者,如果密钥已存在,则根本不添加:

var key = Clusterchar[k];
if(!clusterpoints.ContainsKey(key))
    clusterpoints.Add(key, ClusterPoint);

在哪一行引发异常?因此,请查找两次插入的位置,如果插入的内容已经存在,请使用它来知道正在递归要在绘制事件中保存在面板上绘制的图形,请使用Panel.DrawToBitmap!订阅后,每当控件需要重新绘制自身时(可能在面板顶部显示
Reporttoprint
时),都会引发Paint()事件。某些条件不会改变,最终会将同一个键添加到字典中两次。此外,您还可以听取TaW的建议,使用
.DrawToBitmap
将面板表面绘制为位图(并处理在此过程中创建的对象)。绘制事件用于绘制。看起来你在绘画比赛中没有画画例外是显而易见的;不要在没有检查键的情况下添加到字典中!但是:你到底在那里干什么?谢谢,很管用^^