Allow users to insert a TAB into a TextBox but not newlines

∥☆過路亽.° 提交于 2019-12-11 02:47:44

问题


I want to have a TextBox which does accept the TAB key (and places a TAB, ASCII 0x09, \t accordingly into the textbox) instead of jumping to the next control. The TextBox has a property AcceptsTab, which I have set to true but this does not give the desired result. It turns out the AcceptsTab property only works then Multiline is set to true as well. However I want to have a one-line TextBox which doesn't accept newlines.


回答1:


Here's what you do. Create your own class that inherits from TextBox. In the constructor, set multiline to true, and AcceptsTab to true. Then, override WndProc and use this code:

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == (int)0x102 && m.WParam.ToInt32() == 13)
            {
                return;
            }

            base.WndProc(ref m);
        }

This will block the enter key from being accepted and therefore a new line won't be created. Hacky? yes, but it'll work..

EDIT: I'll explain what this code does. Every windows form and control get a windows message when something happens, like paint, key down etc etc... In this case, I'm looking out for a WM_CHAR message (which is 0x102) which is the message that tells the TextBox which key was pressed. If that's the message, and the WParam == 13, then that means Enter was pressed, in which case, return, do nothing. Else, resume as expected. Makes sense?




回答2:


Sel multilines to true and set the line size to 1. you will get the desired result.



来源:https://stackoverflow.com/questions/374493/allow-users-to-insert-a-tab-into-a-textbox-but-not-newlines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!