c#中WinForm的TextBox迴圈自動滾動樣本

來源:互聯網
上載者:User

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

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中讓文字迴圈滾動:
      /// </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();
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.