首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 中 WinForm 的 TextBox 循環自動捲動示例

     編輯:關於C語言

這個問題來自論壇提問,示範程式碼如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication27
{
    /// <summary>
    /// 示範如何在 TextBox 中讓文字循環捲動:
    /// 作者 jinjazz
    /// 作者 blog: https://blog.csdn.Net/jinjazz
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.textBox1.Clear();
            for (int i = 0; i <= 20; i++)
            {
                this.textBox1.Text += string.Format("{0}:jinjazz__{1} ", i, i);
            }
            this.timer1.Interval = 200;
            this.timer1.Start();
        }

        // 發送訊息
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
        // 取得捲軸位置
        [DllImport("user32")]
        public static extern int GetScrollPos(IntPtr hwnd, int nBar);
        // 設定捲軸位置
        [DllImport("user32.dll")]
        static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        public const int EM_LINESCROLL = 0xb6;
        private void timer1_Tick(object sender, EventArgs e)
        {
            int i = GetScrollPos(this.textBox1.Handle, 1);

            // 向下捲動一行
            SendMessage(this.textBox1.Handle, EM_LINESCROLL, 0, 1); // 0,1 代表垂直捲軸向下捲動

            // 判斷是否有位置變化,如果沒有則說明到了底部,返回開始處
            if (i == GetScrollPos(this.textBox1.Handle, 1))
            {
                // 回到頂部,這裡用 SetScrollPos 似乎有問題,捲軸和文字不是同步更新
                this.textBox1.SelectionStart = 0;
                this.textBox1.SelectionLength = 1;
                this.textBox1.ScrollToCaret();
                this.textBox1.SelectionLength = 0;
            }
            Console.WriteLine(i);
        }

        private void textBox1_MouseEnter(object sender, EventArgs e)
        {
            this.timer1.Stop();
        }

        private void textBox1_MouseLeave(object sender, EventArgs e)
        {
            this.timer1.Start();
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved