在MFC滑块控件中有没有一种方法,当我移动拇指时,它会在默认背景色上填充滑块的背景色

2022-02-24 00:00:00 customization slider background c++ mfc

我正在尝试在mfc中创建自定义滑块。是否有办法使我在移动滑块时,背景颜色会根据滑块拇指在默认背景颜色上的位置而变化,就像.Net中的默认.Net滑块一样。

void rogreen::OnPaint()
{
    CPaintDC dc(this); // device context for painting
                       // TODO: Add your message handler code here
                       // Do not call CStatic::OnPaint() for painting messages

    CRect rectWindow;
    GetClientRect(&rectWindow);


    CRect rect;
    GetClientRect(&rect);

    int r1 = { 0 }, g1 = { 255 }, b1 = { 0 }; //Any start color
    int r2 = { 0 }, g2 = { 0 }, b2 = { 0 }; //Any stop color

    for (int i = 0;i < rect.Height();i++)
    {
        int r, g, b;
        r = r1 + (i * (r2 - r1) / rect.Height());
        g = g1 + (i * (g2 - g1) / rect.Height());
        b = b1 + (i * (b2 - b1) / rect.Height());
        dc.FillSolidRect(0, i, rect.Width(), 1, RGB(r, g, b));
    }
}

解决方案

使用https://docs.microsoft.com/en-us/windows/win32/gdi/drawing-a-shaded-rectangle中的示例,您可以处理如下WM_CTLCOLORSTATIC消息:

case WM_CTLCOLORSTATIC:
{
    if (::GetDlgItem(hDlg, IDC_SLIDER) == (HWND)lParam) {
        HDC hdc = (HDC)wParam;
        RECT r = {};
        ::GetClientRect((HWND)lParam, &r);
        
        // Create an array of TRIVERTEX structures that describe 
        // positional and color values for each vertex. For a rectangle, 
        // only two vertices need to be defined: upper-left and lower-right. 
        TRIVERTEX vertex[2];
        vertex[0].x = 0;
        vertex[0].y = 0;
        vertex[0].Red = 0x0000;
        vertex[0].Green = 0x8000;
        vertex[0].Blue = 0x8000;
        vertex[0].Alpha = 0x0000;

        vertex[1].x = r.right; // 400;
        vertex[1].y = r.bottom; // 40;
        vertex[1].Red = 0x0000;
        vertex[1].Green = 0xd000;
        vertex[1].Blue = 0xd000;
        vertex[1].Alpha = 0x0000;

        // Create a GRADIENT_RECT structure that 
        // references the TRIVERTEX vertices. 
        GRADIENT_RECT gRect;
        gRect.UpperLeft = 0;
        gRect.LowerRight = 1;
        // Draw a shaded rectangle. 
        GradientFill(hdc, vertex, 2, &gRect, 1, GRADIENT_FILL_RECT_V);
        return (INT_PTR)::GetStockObject(NULL_BRUSH);
    }
}

您可以使用滑块的位置计算所需的颜色值。

相关文章