c++ - 如何更改 ListView 的边框颜色

标签 c++ windows listview winapi

我已经使用 win32 api 创建了一个 ListView 。

InitCommonControls();
HWND hwndList1 = CreateWindow(WC_LISTVIEW , L"", WS_VISIBLE|WS_CHILD | LVS_REPORT | LVS_EDITLABELS |  LVS_ICON  | LV_VIEW_TILE |  LVS_EX_GRIDLINES | WS_BORDER | LVS_EX_FULLROWSELECT | ES_LEFT , 10, 10, 300, 190, hwnd, NULL, GetModuleHandle(NULL), 0); 

SendMessageW( hwndList1,
            LVM_SETEXTENDEDLISTVIEWSTYLE,
            LVS_EX_FULLROWSELECT ,
            LVS_EX_FULLROWSELECT );



CreateItem(hwndList1 , (char*)L"fault RS458");
CreateItem(hwndList1 , (char*)L"fault RS455");
CreateColumn(hwndList1 , 0 , (char*)L"Insert column" , 300);

我看到 ListView 周围有黑色边框。我怎样才能改变它的颜色?

最佳答案

您可以使用 SetWindowSubclass 对窗口进行子类化(需要 comctl32.lib)和句柄 WM_NCPAINT绘制控件的非客户区如下:

#include <Windows.h>
#include <CommCtrl.h>

LRESULT CALLBACK ListViewProc(HWND hwnd, 
    UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
    switch(msg)
    {
    case WM_NCPAINT:
    {
        RECT rc;
        GetWindowRect(hwnd, &rc);
        OffsetRect(&rc, -rc.left, -rc.top);
        auto hdc = GetWindowDC(hwnd);
        auto hpen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
        auto oldpen = SelectObject(hdc, hpen);
        SelectObject(hdc, GetStockObject(NULL_BRUSH));
        Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom);//draw red frame
        SelectObject(hdc, oldpen);
        DeleteObject(oldpen);
        ReleaseDC(hwnd, hdc);

        //*** EDIT
        //documentation says we should return 0
        //but that causes problem with vertical scrollbar
        //maybe we should break for this subclass case

        break; //not return 0!
    }

    case WM_NCDESTROY:
        RemoveWindowSubclass(hwnd, ListViewProc, 0);
        break;
    }

    return DefSubclassProc(hwnd, msg, wp, lp);
}
...
HWND hwndList1 = CreateWindow(...); 
SetWindowSubclass(hwndList1, ListViewProc, 0, NULL);

<子> 旁注,(char*)L"text" 没有意义。使用 ANSI((char*)"text")或 Unicode((wchar_t*)L"text",推荐)。您可以更改 CreateItem 以接受 const wchar_t*,然后在最后为 LVITEM 转换为 (wchar_t*)避免错误的步骤。

编辑
WM_NCPAINT 会中断,不会返回零。

关于c++ - 如何更改 ListView 的边框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57537823/

相关文章:

c++ 可以使用 fstream infile 从最近使用的 ofstream outfile 中收集数据吗?

c++ - vkCreateSwapchainKHR() : surface capabilities not retrieved for this physical device

iphone - 在 Windows 上模拟 iphone?

android - 具有数据收集功能的 Titanium ListViews

python - 在python中拆分列表的项目

c++ - 数组 : convert index of one dimensional array to a vector index of a multidimensional array

c++ - 为什么通过函数指针调用成员函数时需要 "this"前缀?

windows - 如何从 WSL(Linux 的 Windows 子系统)访问 aws 配置文件?

Android 列表适配器问题

c++ - Excel 调用 C++ 程序的函数