gpt4 book ai didi

c# - RichTextBox 在面板滚动时自动垂直滚动 c#

转载 作者:行者123 更新时间:2023-11-30 17:03:47 24 4
gpt4 key购买 nike

我在 WinForm 的面板内有一个 RichTextBox。我想隐藏RichTextBox的垂直滚动条,使其滚动与容器面板的垂直滚动条同步;每当 textbox 中的文本溢出时,面板的滚动条就会出现,每当我滚动面板的滚动条时,textbox 就会滚动。如何实现?

最佳答案

正如我在评论中所说,我们必须处理 win32 消息并使用一些 hack。我已经使用了我所有关于 win32 消息和控制 hack/自定义的知识,为您制作了这个演示。它并不完整,当然也不会像 RichTextBox 的标准滚动条那样完美。缺点是如果你一直按住箭头键,滚动条拇指不会向右移动,但是如果你正常按下箭头键,滚动条拇指会像标准滚动条一样将插入符号移动到 View 中。您可以自己尝试代码以查看它的实际效果:

public class Form1 : Form {
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
public Form1(){
InitializeComponent();
//initialize some properties for your richTextBox1 (this should be added as a child of your panel1)
richTextBox1.ScrollBars = RichTextBoxScrollBars.Horizontal;
richTextBox1.BorderStyle = BorderStyle.None;
richTextBox1.Dock = DockStyle.Top;
richTextBox1.MinimumSize = new Size(panel1.Width, panel1.Height - 2);
//initialize some properties for your panel1
panel1.AutoScroll = true;
panel1.BorderStyle = BorderStyle.FixedSingle;
//If the size of panel1 is changed, we have to update the MinimumSize of richTextBox1.
panel1.SizeChanged += (s,e) => {
richTextBox1.MinimumSize = new Size(panel1.Width, panel1.Height - 2);
};
new NativeRichTextBox() { Parent = panel1 }.AssignHandle(richTextBox1.Handle);
hidden.Parent = panel1;
}
//hidden control of panel1 is used to scroll the thumb when the KeyUp of richTextBox1 is raised.
Control hidden = new Control();
//this is used to hook into the message loop of the richTextBox1
public class NativeRichTextBox : NativeWindow
{
public Panel Parent;
protected override void WndProc(ref Message m)
{

if (m.Msg == 0x20a)//WM_MOUSEWHEEL = 0x20a
{
if (Parent != null)
{
SendMessage(Parent.Handle, m.Msg, m.WParam, m.LParam);
return;
}
}
base.WndProc(ref m);
}
}
//ContentsResized event handler of your richTextBox1
private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e)
{
richTextBox1.Height = e.NewRectangle.Height + 5;
}
//KeyUp event handler of your richTextBox1
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
Point p = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
hidden.Top = panel1.PointToClient(richTextBox1.PointToScreen(p)).Y;
hidden.Height = (int) richTextBox1.SelectionFont.Height;
panel1.ScrollControlIntoView(hidden);
}
}

注意:您必须使用代码或由设计师。

关于c# - RichTextBox 在面板滚动时自动垂直滚动 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18246459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com