让ListBox自动滚动到底部

时间:2022-11-29 19:42:28

在ListBox中添加一条记录(ListBox.Items.Add方法)后,滚动条会自动回到顶部。我们可能更希望它自动滚动到底部,本文简要介绍几种方法。

方法1:

在添加记录后,先选择最后一条记录,滚动条会自动到底部,再取消选择。缺点是需两次设置选中条目,中间可能会出现反色的动画,影响美观。

  
  
  
this .listBox1.Items.Add( " new line " );
this .listBox1.SelectedIndex = this .listBox1.Items.Count - 1 ;
this .listBox1.SelectedIndex = - 1 ;

方法2:

通过计算ListBox显示的行数,设置TopIndex属性(ListBox中第一个可见项的索引)而达到目的。

  
  
  
this .listBox1.Items.Add( " new line " );
this .listBox1.TopIndex = this .listBox1.Items.Count - ( int )( this .listBox1.Height / this .listBox1.ItemHeight);

对方法2的改进:

在添加新记录前,先计算滚动条是否在底部,从而决定添加后是否自动滚动。既可以在需要时实现自动滚动,又不会在频繁添加记录时干扰用户对滚动条的控制。

  
  
  
bool scroll = false ;
if ( this .listBox1.TopIndex == this .listBox1.Items.Count - ( int )( this .listBox1.Height / this .listBox1.ItemHeight)) scroll = true ;
this .listBox1.Items.Add( " new line " );
if (scroll) this .listBox1.TopIndex = this .listBox1.Items.Count - ( int )( this .listBox1.Height / this .listBox1.ItemHeight);

方法3:

向listBox1的垂直滚动条发送滚动的消息。

  
  
  
using System.Runtime.InteropServices;

[DllImport(
" User32.dll " )]
private static extern Int32 SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
public const int WM_VSCROLL = 0x0115 ;
public const int SB_BOTTOM = 7 ;

SendMessage(listBox1.Handle, WM_VSCROLL, SB_LINEDOWN,
0 );