聯系我們 - 廣告服務 - 聯系電話:
您的當前位置: > 關注 > > 正文

環球熱門:自定義控件GDI繪制在主程序報錯System怎么解決?解決方法

來源:CSDN 時間:2023-01-12 10:20:12


(資料圖)

C#自定義控件GDI繪制在主程序報錯System.ArgumentException;

我的繪制圖片內容大概如下:

private Bitmap backGroundImage=null;private Bitmap prospectImage=null;private Graphics graphics = null;/// /// 在背景上畫前景/// private void drawProspect(){    try    {        if(prospectImage!=null)  //注釋            prospectImage.Dispose();  //注釋        prospectImage = backGroundImage.Clone() as Bitmap;        using (graphics = Graphics.FromImage(prospectImage))        {            //畫你所需要的內容        }        pictrueBox1.Image=prospectImage;    }catch(Exception ee)    {        }}

在線程高速(50ms以下一次)運行下就會隨機報這個錯 :

System.ArgumentException: 參數無效。.

在 System.Drawing.Image.get_Width()    在 System.Drawing.Image.get_Size()    在 System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)    在 System.Windows.Forms.PictureBox.get_ImageRectangle()    在 System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)    在 System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)    在 System.Windows.Forms.Control.WmPaint(Message& m)    在 System.Windows.Forms.Control.WndProc(Message& m)    在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)    在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)    在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

這種錯誤連錯在哪在代碼哪一行都不知道,連try也無法捕捉到。

經過各種嘗試,發現我不寫釋放prospectImage那兩行代碼時,就不會報這個錯(就是上面代碼中有注釋的兩行代碼)。

但是這樣的話,內存就會瘋漲,不合理。于是就有了下面的解決方法:

private Bitmap backGroundImage=null;private Bitmap prospectImage=null;private Image prospectImageCpoy = null;private Graphics graphics = null;/// /// 在背景上畫前景/// private void drawProspect(){    try    {        //if(prospectImage!=null)  //注釋        //   prospectImage.Dispose();  //注釋        prospectImage = backGroundImage.Clone() as Bitmap;        using (graphics = Graphics.FromImage(prospectImage))        {            //畫你所需要的內容        }       prospectImageCpoy = pictureBox1.Image;//保存上一次的圖片       pictureBox1.Image = prospectImage;//覆蓋上一次的圖片       prospectImageCpoy.Dispose();//釋放上一次的圖片    }catch(Exception ee)    {        }}

內存不再瘋漲了,運行也穩定了,完美解決。

責任編輯:

標簽:

相關推薦:

精彩放送:

新聞聚焦
Top 岛国精品在线