多行文本框不会将光标移动到末尾

时间:2016-10-05 12:26:30

标签: c# scroll visual-studio-2015 textbox

我有一个多行文本框,我从txt文件填充文本(表单加载)。我试图以任何可能的方式将垂直滚动移动到底部(因为有很多行)。

我尝试使用ScrollToCaret附加文本,更改选择以及我找到的其他几种方法,但不是它们正在工作。

我已经尝试将我发现的所有内容移动到textChanged事件中并在填充文本框后立即放置它,但它仍然没有滚动到底部。

每当我使用任何可能有效的东西时,位置仍然在文本框文本的开头。

有什么建议吗?

提前致谢

这是我用来将文本添加到文本框的代码

if (File.Exists(path))
{

    txtLog.AppendText(File.ReadAllText(path));
    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden | FileAttributes.ReadOnly);

}

3 个答案:

答案 0 :(得分:0)

将以下方法添加到您的代码中。 并确保在代码顶部添加using System.Runtime.InteropServices;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
        private const int WM_VSCROLL = 277;
        private const int SB_PAGEBOTTOM = 7;

        public static void ScrollToBottom(TextBox textBox)
        {
            SendMessage(textBox.Handle, WM_VSCROLL, (IntPtr)SB_PAGEBOTTOM, IntPtr.Zero);
        }

将代码更改为

if (File.Exists(path))
{

    txtLog.AppendText(File.ReadAllText(path));
    ScrollToBottom(txtLog);
    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden | FileAttributes.ReadOnly);

}

答案 1 :(得分:0)

将TextBox更改为RichTextBox可以解决您的问题。

答案 2 :(得分:0)

如果您仍想使用常规TextBox,则以下内容应该有效:

txtLog.AppendText(File.ReadAllText(path));
Dispatcher.InvokeAsync(txtLog.ScrollToEnd, DispatcherPriority.Background);
相关问题