在 winforms 中使用按钮移动水平滚动条或列表框

Move Horizental ScrollBar or a ListBox with a button in winforms

我在 visual studio 2017 年创建了一个 winforms 应用程序,我正在使用 List 填充列表框。

我将多列 属性 设置为 true。由于我的列表中有很多字符串,因此框底部出现了一个水平滚动条。

我正在创建的应用程序应该在平板电脑上运行,因此滚动条不容易用手指导航。

我的问题是,有没有办法可以使用按钮控制此滚动条?

您可以发送 WM_HSCROLL message to the ListBox to scroll it. To do so, you should first get the scroll position by calling GetScrollInfo 方法。

以下代码向右滚动 ListBox, 1 列:

var info = new SCROLLINFO() { fMask = ScrollInfoMask.SIF_ALL };
GetScrollInfo(listBox1.Handle, SBOrientation.SB_HORZ, ref info);
var wparam = ((uint)(info.nPos + 1) << 16) | (SB_THUMBPOSITION & 0xffff);
SendMessage(listBox1.Handle, WM_HSCROLL, wparam, 0);

要向左滚动一列,请使用 info.nPos - 1

这是您需要的声明:

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg,
    uint wParam, uint lParam);

[StructLayout(LayoutKind.Sequential)]
struct SCROLLINFO {
    public uint cbSize;
    public ScrollInfoMask fMask;
    public int nMin;
    public int nMax;
    public uint nPage;
    public int nPos;
    public int nTrackPos;
}

public enum ScrollInfoMask : uint {
    SIF_RANGE = 0x1,
    SIF_PAGE = 0x2,
    SIF_POS = 0x4,
    SIF_DISABLENOSCROLL = 0x8,
    SIF_TRACKPOS = 0x10,
    SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS),
}

[DllImport("user32.dll")]
private static extern bool GetScrollInfo(IntPtr hwnd, 
    SBOrientation fnBar, ref SCROLLINFO lpsi);

public enum SBOrientation : int {
    SB_HORZ = 0x0,
    SB_VERT = 0x1,
}

const uint WM_HSCROLL = 0x0114;
const uint SB_THUMBPOSITION = 4;

是的,可以在 Buttons 的帮助下控制您期望的行为。

从右向左移动-

private void btnLeft_Click(object sender, EventArgs e)
{
    int visibleItemsInColumn = listBox1.ClientSize.Height / listBox1.ItemHeight; //No of items in each column. In this case - 5
    listBox1.TopIndex = listBox1.TopIndex - visibleItemsInColumn;

}

从左到右移动-

private void btnRight_Click(object sender, EventArgs e)
{
    int visibleItemsInColumn = listBox1.ClientSize.Height / listBox1.ItemHeight;
    listBox1.TopIndex = listBox1.TopIndex + visibleItemsInColumn;
}

What it actually does is every time you click on button, It increases/decreases the TopIndex by the total elements per columns. So on each clicks, you move one column either left or right.