c#中WinForm的TextBox循环自动滚动示例

本文介绍了一个简单的方法,使得TextBox中的文本可以实现循环滚动效果。通过使用.NET Framework提供的API,如 SendMessage 和 GetScrollPos,作者实现了当文本到达底部时自动滚回到顶部的功能。此代码适用于Windows Forms应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个问题来自论坛提问,演示代码如下

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: http://blog.youkuaiyun.com/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(IntPtrhWnd, int wMsg, int wParam, int lParam);
// 获取滚动条位置
[DllImport( " user32 " )]
public static extern int GetScrollPos(IntPtrhwnd, int nBar);
// 设置滚动条位置
[DllImport( " user32.dll " )]
static extern int SetScrollPos(IntPtrhWnd, int nBar,
int nPos, bool bRedraw);

public const int EM_LINESCROLL = 0xb6 ;

private void timer1_Tick( object sender,EventArgse)
... {
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,EventArgse)
... {
this .timer1.Stop();
}


private void textBox1_MouseLeave( object sender,EventArgse)
... {
this .timer1.Start();
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值