[英]Auto vertical scrolling of RichTextBox on panel scrolling c#
我在WinForm
的面板中有一個RichTextBox
。 我想隱藏RichTextBox
的垂直滾動條,並將其滾動與容器面板的垂直滾動條同步; 每當文本在textbox
溢出時,面板的滾動條就會出現;每當我滾動面板的滾動條時, textbox
就會滾動。 如何實現呢?
正如我在評論中所說,我們必須處理win32消息並使用一些技巧。 我已經使用了所有關於win32消息的知識,並在winforms
控制了hack /自定義,為您制作了這個演示。 它並不完整,當然也不會像RichTextBox
的標准滾動條那樣完美。 不足之處在於,如果您一直按住箭頭鍵,滾動條的拇指將不會向右移動,但是,如果您通常按箭頭鍵,滾動條的拇指將插入符插入到標准滾動條中。 您可以自己嘗試該代碼以查看實際效果:
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);
}
}
注意:您必須使用代碼或通過設計器為richTextBox1
注冊事件處理程序ContentsResized
和KeyUp
。
為了隱藏滾動條,你可以做
richTextBox1.ScrollBars = RichTextBoxScrollBars.None;
但是問題在於它使文本變形。 所以你也需要
richTextBox1.WordWrap = false;
一旦完成,剩下的事情就不那么容易了。
注冊面板滾動事件,並更改富文本框中的滾動。 問題是您不能只更改richTextBox
滾動偏移量,因此可以使用Select
方法跳轉到所需的位置。 您可以使用行的長度來知道所需的scrollBar
大小。
最后,這將是一個艱苦的工作。 祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.