我正在寻找一些解决方案来使文本适合框架。我不希望框架是圆形的。我只需要允许用户在其中输入文本。
尝试用 C# 和 .net 形式编写程序。 问题是我不知道该使用什么,因为我用多行和自动换行检查了 richTextBox,但是某个阶段的格式变得可滚动,这是我不想要的。文本应该只适合该图形。
我有什么:
我需要什么:
我希望文本仅适合给定格式的大小而不滚动。
我已经尝试使用 RichTextBox,但用户仍然可以在半行中输入一些内容,结果会将大量文本发送到文本被剪切的行。
public class CustomTextBox : RichTextBox
{
public CustomTextBox()
{
Location = new Point(54, 50);
Multiline = true;
WordWrap = true;
Size = new Size(600, 120);
Dock = DockStyle.None;
BorderStyle = BorderStyle.None;
ScrollBars = RichTextBoxScrollBars.None;
ForeColor = Color.Black;
BackColor = Color.Yellow;
}
}
private void InitializeForm()
{
CustomTextBox customBox = new CustomTextBox()
customBox.TextChanged += CustomBox_TextChanged;
this.Controls.Add(customBox)
}
private void CustomBox_TextChanged(object sender, EventArgs e)
{
RichTextBox rtb = sender as RichTextBox;
int lastCharIndex = rtb.TextLength - 1;
if (lastCharIndex <0)
{
return;
}
Point lastCharPosition = rtb.GetPositionFromCharIndex(lastCharIndex);
if (lastCharPosition.Y + rtb.Font.Height >= rtb.ClientSize.Height && lastCharPosition.X + rtb.Font.SizeInPoints >= rtb.ClientSize.Width)
{
rtb.ReadOnly = true;
}
您可以测试一些建议和修改后的自定义控件。
创建控件时,需要在指定的容器中指定Location
和
Size
属性。控件本身不关心其父级内部的布局。
private void InitializeForm()
{
var customBox = new CustomTextBox() {
Font = new Font("Segoe UI", 20f, FontStyle.Regular, GraphicsUnit.Point);
Location = new Point(54, 50);
Size = new Size(600, 120);
}
Controls.Add(customBox)
}
根据目前的情况,我建议:
ES_AUTOVSCROLL
中的控件样式中删除了
ES_AUTOHSCROLL
和
CreateParams
。
public class CustomRichTextBox : RichTextBox {
const int ES_AUTOVSCROLL = 0x0040;
const int ES_AUTOHSCROLL = 0x0080;
TextFormatFlags flags = TextFormatFlags.WordBreak |
TextFormatFlags.TextBoxControl;
public CustomRichTextBox() {
BorderStyle = BorderStyle.None;
ScrollBars = RichTextBoxScrollBars.None;
ForeColor = Color.Black;
BackColor = Color.Yellow;
}
protected override CreateParams CreateParams {
get {
var cp = base.CreateParams;
// Disable auto-scroll to last insert line
cp.Style &= ~(ES_AUTOVSCROLL | ES_AUTOHSCROLL);
return cp;
}
}
protected override bool ProcessCmdKey(ref Message m, Keys keyData) {
if (keyData == (Keys)Shortcut.CtrlV || keyData == (Keys)Shortcut.ShiftIns) {
return true; // Suppress CTRL+V & SHIFT+INS
}
return base.ProcessCmdKey(ref m, keyData);
}
protected override void OnKeyDown(KeyEventArgs e) {
if (!IsInputKey(e.KeyData) && e.KeyCode != Keys.Delete) {
var newText = new StringBuilder(Text, TextLength + 2)
.Insert(SelectionStart, e.KeyCode == Keys.Enter ? "\nM" : (char)e.KeyCode);
var textHeight = TextRenderer.MeasureText(newText.ToString(), Font, ClientSize, flags).Height;
if (textHeight > (ClientSize.Height + 1)) { // (0 to n-1) + 1
e.SuppressKeyPress = true;
}
}
base.OnKeyDown(e);
}
}