TextBox.Multiline缩进现象不是bug(文档解读,帮助你理解MSDN难懂的词句)

写这篇文章是为了让大家弄明白MSDN文档中的一个比较让人难懂的词句。

不知道大家在平时翻看MSDN文档的TextBox.Multiline属性的时候是否注意到下面这段话:

http://msdn.microsoft.com/en-us/library/12w624ff.aspx

When the font is changed, any indentation that you have defined does not appear. To get indentation, set Multiline to true and override WM_SETFONT without calling the base class so that SETMARGINS is not called.

有很多人没有注意到这句话,也有许多人看到了这句话,但不理解其中的意思,搞得大家迷迷糊糊的,MSDN文档总是这样,经常让人感觉不知所云,而且还不加解释。

下面进入正题:

我前几天接到一个case,客户说在使用TextBox的时候发现了一个现象,疑似bug。

现象是这样的:

当你设置Multiline属性为true时,并设置一下字体为一些特殊的字体,如Arial,可以适当调大字体,这样我们会更容易看到现象。

运行程序,你会发现字的前面有一块空白(缩进)。而又的字体却不会显示出这块空白。而且客户还找出来了一个ms connect上的case,说这个是一个bug。

确实,ms connect有时候做的也不怎么理想,竟然把客户的case关掉,没有理想的理由,也没有说这个是否是一个bug。让大家很是猜疑。

我没办法啊,只好查看这个属性,结果就让我看到了上面那段英文注释。说实话,开始我也没读懂,也不知道他说的是什么地方。后来过了几天,我又打开了这个case,突然灵光一线,啊哈,有了。

我马上打开Reflector来查看TextBox的WndProc方法,果然,秘密就在这个事件处理方法里面。

当设置TextBox中的文字的时候,代码回根据Multiline 属性来判断是否执行设置字体格式,如果此属性为假,那么就不进行缩进,相反,则设置缩进。

原来是这样啊,有了!

我们可以实现一个扩展TextBox来自定义是否设置缩进。我只需要按照上面的那段文档来做就可以了,具体的代码实现可以看下面我给客户的回复。

至此,一个文档理解和解释不足导致的,疑似bug,被我解决了。哈哈哈哈哈哈哈哈。。。。。。。。。

(很有成就感哦,嘿嘿,哈哈。。。)

EM_SETMARGINS Message

Sets the widths of the left and right margins for an edit control. The message redraws the control to reflect the new margins. You can send this message to either an edit control or a rich edit control.

SendMessage Function

Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.

You will need to know some p/invoke knowledge when you want use the native function above in your managed code:

Platform Invoke Tutorial

I just wrote a simple demo which will help you to solve your request. You just can reference this code in your project, and then the TextBoxEx instance will not show any indentation since I let the code also send the set margins message which will not also be sent in the built in TextBox control in .net framework when you set Multiline property true.

 

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/691ec3d7-e28d-41c6-bac9-4edadd831340

这个是此case的链接,有兴趣的朋友可以进去看看。

PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

MSDN论坛好帮手

posted @ 2011-03-07 20:31  Mike Dos Zhang  阅读(371)  评论(1编辑  收藏  举报