【WinForm】Dev 关于改变控件可见属性时发生异常的问题 System.ArgumentNullException:Value cannot be null.

错误提示:

System.ArgumentNullException:Value cannot be null.

Parameter name:dc

at System.Windows.Forms.TextRenderer.MesureText(IDeviceContext dc, String text, Font font, Size proposedSize, TextFormatFlags flags)

……(下面连着一大串异常信息)

 

根据错误提示,是因为dc这个参数等于null了,导致调用TextRenderer.MesureText()这个函数报错。上网搜了一下这个函数的用法,可以看一下:

http://www.voidcn.com/article/p-fmczttqu-nz.html

官网的解释:

https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.forms.textrenderer.drawtext?redirectedfrom=MSDN&view=netcore-3.1#System_Windows_Forms_TextRenderer_DrawText_System_Drawing_IDeviceContext_System_String_System_Drawing_Font_System_Drawing_Rectangle_System_Drawing_Color_System_Drawing_Color_System_Windows_Forms_TextFormatFlags_

 

总之,这个函数时用于在 Windows 窗体控件上测量和绘制文本,而dc这个参数是绘制文本所使用的设备上下文(Device Context)。设备上下文或许可以理解为要绘制控件的画布。此时dc为null,说明程序在此处没有获取到设备上下文。

根据网上查阅到的资料,我猜测,是因为用TextRenderer.MesureText()绘制控件需要一定时间,而程序频繁对该控件进行重绘,则可能会发生,另一处还未释放设备上下文时(释放函数:ReleaseDC()),这一处就再次调用重绘函数的情况,所以导致dc = null。

 

解决方案:

源代码中造成异常的语句为:

控件.Visible = false;

 

至今没有想到什么根本的解决方法,只是换了个思路:既然是控件重绘导致的问题,则避免控件重新绘制即可:

控件.ReadOnly = false;

 

功能实现就好啦~haha

 

学习网址:

https://zhidao.baidu.com/question/264795683.html

设备上下文:https://docs.microsoft.com/zh-cn/cpp/mfc/device-contexts?view=vs-2019

https://www.cnblogs.com/lisuyun/articles/3356696.html

 

posted @ 2020-09-09 15:42  不溯流光  阅读(1936)  评论(0编辑  收藏  举报