DEV Community

海前 王
海前 王

Posted on

lvs

BOOL CMyDialog::OnInitDialog()
{
    CDialog::OnInitDialog();

    // 获取对话框的客户区大小
    RECT rect;
    GetClientRect(&rect);

    // 创建 ListCtrl 控件
    m_ListCtrl.Create(WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_OWNERDRAW, 
                      CRect(0, 0, rect.right, rect.bottom), this, IDC_LISTCTRL);

    // 添加列
    m_ListCtrl.InsertColumn(0, _T("Column 1"), LVCFMT_LEFT, 100);
    m_ListCtrl.InsertColumn(1, _T("Column 2"), LVCFMT_LEFT, 100);

    // 添加项
    for (int i = 0; i < 50; ++i)
    {
        CString str;
        str.Format(_T("Item %d"), i + 1);
        m_ListCtrl.InsertItem(i, str);
        m_ListCtrl.SetItemText(i, 1, _T("Detail"));
    }

    // 初始化滚动条
    SCROLLINFO si = { sizeof(si) };
    si.fMask = SIF_RANGE | SIF_PAGE;
    si.nMin = 0;
    si.nMax = 50;
    si.nPage = 10; // Number of visible items
    m_ListCtrl.SetScrollInfo(SB_VERT, &si, TRUE);

    return TRUE;
}
void CMyDialog::OnSize(UINT nType, int cx, int cy)
{
    CDialog::OnSize(nType, cx, cy);

    if (m_ListCtrl.GetSafeHwnd())
    {
        m_ListCtrl.MoveWindow(0, 0, cx, cy);

        SCROLLINFO si = { sizeof(si) };
        si.fMask = SIF_RANGE | SIF_PAGE;
        si.nMin = 0;
        si.nMax = 50;
        si.nPage = cy / cyChar; // Adjust the page size based on the dialog size
        m_ListCtrl.SetScrollInfo(SB_VERT, &si, TRUE);
    }
}

void CMyDialog::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
    int nScrollPos = m_ListCtrl.GetScrollPos(SB_VERT);

    switch (nSBCode)
    {
    case SB_LINEDOWN:
        nScrollPos += 1;
        break;
    case SB_LINEUP:
        nScrollPos -= 1;
        break;
    case SB_PAGEDOWN:
        nScrollPos += m_ListCtrl.GetScrollInfo(SB_VERT).nPage;
        break;
    case SB_PAGEUP:
        nScrollPos -= m_ListCtrl.GetScrollInfo(SB_VERT).nPage;
        break;
    case SB_THUMBPOSITION:
        nScrollPos = nPos;
        break;
    }

    // Ensure the scroll position is within valid range
    nScrollPos = max(0, min(nScrollPos, 50 - m_ListCtrl.GetScrollInfo(SB_VERT).nPage));

    m_ListCtrl.SetScrollPos(SB_VERT, nScrollPos);
    m_ListCtrl.Scroll(CSize(0, (nScrollPos - m_ListCtrl.GetScrollPos(SB_VERT)) * cyChar));

    CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}
BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
    ON_WM_SIZE()
    ON_WM_VSCROLL()
END_MESSAGE_MAP()



Enter fullscreen mode Exit fullscreen mode

Top comments (0)