要實現RichTextBox內容的自滾動,首先要建立一個WPF Application 的工程,這裡工程命名為FreeScroll。
1.應用軟體:VS2010
2. 程式完成的功能:
2.1 在richtextBox中載入Xaml檔案
2.2 設定捲動速度
2.3 滾動
2.4 滑鼠雙擊停止滾動
3. 程式用到的控制項:RichTextBox,Button,Label,TextBox
4.程式的實現
4.1 控制項布局
WPF中布局好的控制項圖如下:
4.2 實現控制項的響應函數
代碼
namespace FreeScroll {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
textBox1.Text="";
}
//載入檔案
private void Load_Click(object sender, RoutedEventArgs e) {
tmp =0;
if (this.timer !=null) { timer.Tick -= new EventHandler(timer_Tick); }
OpenFileDialog openDialog=new OpenFileDialog ();
if (openDialog.ShowDialog()==true )
{
using(FileStream fs=new FileStream (openDialog.FileName,FileMode.Open))
{
richTextBox1.Document=XamlReader.Load(fs) as FlowDocument;
richTextBox1.Background =richTextBox1.Document.Background;
}
}
}
//實現滾動
private void Scroll_Click(object sender, RoutedEventArgs e) {
if (timer!=null)
{
timer.Tick-=new EventHandler (timer_Tick);
}
int timeInterval;
if (textBox1.Text != "") {
timeInterval = System.Int32.Parse(textBox1.Text);
if (timeInterval >= 0) {
timer.Interval = new TimeSpan(0, 0, 0, 0, timeInterval);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
} else {
MessageBox.Show("請輸入合適的時間間隔!");
}
} else {
MessageBox.Show("請輸入合適的時間間隔!");
}
}
void timer_Tick(object sender, EventArgs e) {
this.richTextBox1.ScrollToVerticalOffset(tmp++);
}
//滑鼠雙擊停止滾動
private void richTextBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
timer.Tick -=new EventHandler(timer_Tick);
}
double tmp = 0;
DispatcherTimer timer = new DispatcherTimer();
}
}