Dan*_*n W 5 c# winapi scroll scrollbar richtextbox
我之前的帖子显示了如何在RichTextbox中获取水平或垂直滚动条的位置.但是,这些仅在启用滚动条时有效.如果将滚动条设置为无(通过richTextBox1.ScrollBars = RichTextBoxScrollBars.None;),则仍然可以向下滚动框的底部(如果禁用WordWrap则向右滚动).但是,getVerticalScroll()和getHorizontalScroll()方法(如我发布的链接中所示)现在只返回0.他们似乎需要"看到"滚动条才能真正起作用.
那么当滚动条被禁用时,如何获取(并设置)"滚动位置"?
RichTextBox类有几个辅助方法,可以让您发现窗口内文本的位置.这是您需要在此处使用的内容,因为您不再需要滚动条的直接反馈.
你可以找到哪一行显示为RichTextBox.GetCharIndexFromPosition()的第一个可见行,以找到第一个可见字符,然后是GetLineFromCharIndex()以找出包含该字符的行:
public static double GetVerticalScrollPos(RichTextBox box) {
int index = box.GetCharIndexFromPosition(new Point(1, 1));
int topline = box.GetLineFromCharIndex(index);
int lines = box.Lines.Length;
return lines == 0 ? 0 : 100.0 * topline / lines;
}
Run Code Online (Sandbox Code Playgroud)
通过查看插入符当前所在的行,可以找到水平滚动位置.并将行的开头映射回位置:
public static double GetHorizontalScrollPos(RichTextBox box) {
int index = box.SelectionStart;
int line = box.GetLineFromCharIndex(index);
int start = box.GetFirstCharIndexFromLine(line);
Point pos = box.GetPositionFromCharIndex(start);
return 100 * (1 - pos.X) / box.ClientSize.Width;
}
Run Code Online (Sandbox Code Playgroud)
您可能想要重新定义100%的含义,您的原始问题没有给出任何指导.
这个问题涉及XY问题的各个方面,它说你真正想做的是用更大的滚动条替换滚动条.不要忽视这个愚蠢的简单解决方案,你可以通过正确放置它们来覆盖现有的解决方案,使它们重叠并隐藏它们.你只需要改变边框,这样就不那么明显了.
我想你会在这里找到一些有趣的东西.它是在.Net 中RichEdit使用的描述RichTextBox.
还解决了你的问题:
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(POINT)));
Marshal.StructureToPtr(new POINT(), ptr, false);
SendMessage(this.richTextBox1.Handle, EM_GETSCROLLPOS, IntPtr.Zero, ptr);
var point = (POINT)Marshal.PtrToStructure(ptr, typeof(POINT));
Marshal.FreeHGlobal(ptr);
Run Code Online (Sandbox Code Playgroud)
哪里:
EM_GETSCROLLPOS = WM_USER + 221
Run Code Online (Sandbox Code Playgroud)
和pinvoke.net的POINT结构.