gpt4 book ai didi

c++ - 为什么鼠标按下会阻止组件的重新绘制?

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:54 31 4
gpt4 key购买 nike

我正在尝试创建一个自定义组件来捕获鼠标事件,尤其是 MouseMove。

我从 TWinControl 派生,但我也尝试过 TGraphicControlTCustomControlTTrackBar 等。

我的问题是当我在组件上按住鼠标时,它没有被重新绘制。

Paint() 方法在我释放鼠标按钮之前不会被调用,即使我调用了 Invalidate()

TrackBar 是我想要制作的最接近的组件。您选择勾号,然后用鼠标移动它。但是您不必释放鼠标就可以看到刻度线同时移动(再次绘制组件)。

如果我直接调用 Paint(),它可以工作,但背景不会被删除。

我错过了什么?

编辑:我再次尝试并确认我是否按住鼠标,Invalidate();仅当我松开鼠标时才会考虑调用。用我下面的代码试试你自己,paint 只在发布时调用:

__fastcall TMyCustomComponent::TMyCustomComponent(TComponent* Owner)
: TCustomTransparentControl(Owner)
{
mValue = 0;
}

void __fastcall TMyCustomComponent::MouseDown(System::Uitypes::TMouseButton Button, System::Classes::TShiftState Shift, int X, int Y)
{
if (Button == mbLeft)
{
mValueStart = 0;
}
}

void __fastcall TMyCustomComponent::MouseMove(System::Classes::TShiftState Shift, int X, int Y)
{
Invalidate();
}

void __fastcall TMyCustomComponent::Paint(void)
{
TGraphicControl::Paint();
Canvas->Font->Name = "Arial";
Canvas->Font->Size = 8;
Canvas->Font->Style = TFontStyles() << fsBold;
Canvas->Font->Color = clInfoText;
Canvas->Brush->Color = clInfoBk;
Canvas->FillRect(TRect(0, 0, 104, 21));
mValue++;
Canvas->TextOut(0, 2, AnsiString(mValue));
Canvas->Brush->Color = clBtnShadow;
}

最佳答案

以下对我来说效果很好:

__fastcall TMyCustomComponent::TMyCustomComponent(TComponent* Owner)
: TCustomTransparentControl(Owner)
{
mValue = 0;
InterceptMouse = true; // <-- needed for TCustomTransparentControl to trigger Mouse...() methods!
}

void __fastcall TMyCustomComponent::MouseDown(System::Uitypes::TMouseButton Button, System::Classes::TShiftState Shift, int X, int Y)
{
if (Button == mbLeft)
{
mValue = 0;
Invalidate();
}
TCustomTransparentControl::MouseDown(Button, Shift, X, Y);
}

void __fastcall TMyCustomComponent::MouseMove(System::Classes::TShiftState Shift, int X, int Y)
{
++mValue;
Invalidate();
TCustomTransparentControl::MouseMove(Shift, X, Y);
}

void __fastcall TMyCustomComponent::Paint()
{
TCustomTransparentControl::Paint();
Canvas->Font->Name = "Arial";
Canvas->Font->Size = 8;
Canvas->Font->Style = TFontStyles() << fsBold;
Canvas->Font->Color = clInfoText;
Canvas->Brush->Color = clInfoBk;
Canvas->FillRect(TRect(0, 0, ClientWidth, ClientHeight));
Canvas->TextOut(0, 2, String(mValue));
Canvas->Brush->Color = clBtnShadow;
}

按下鼠标左键会将 mValue 重置为 0 并绘制它。在控件周围移动鼠标会增加 mValue 并绘制它,无论是否按住鼠标按钮。

关于c++ - 为什么鼠标按下会阻止组件的重新绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091403/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com