Delphi - Changing TComboBox's OnChange

2019-08-12 03:36发布

问题:

I want to change the TComboBox so that if I type text into it or manually set the Text property it will trigger the OnChange event.

As it is now, doing ComboBox.Text := 'blah' doesn't trigger the OnChange event, nor does typing into the box.

I tried creating a TComboBox descendant, which I assume is the right approach, but I'm not really sure how to change what triggers the events.

回答1:

To the best of my knowledge, typing into a combo box will result in the OnChange event firing. But it is true that modifying the text property does not.

The way I would go about getting OnChange to fire for your combo box is to handle the CM_TEXTCHANGED message. The handler for this needs to call the Change method which will then call OnChange, if it has been assigned.

As a simple example, here's an interposer class implementation:

type
  TComboBox = class(StdCtrls.TComboBox)
  protected
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
  end;

procedure TComboBox.CMTextChanged(var Message: TMessage);
begin
  inherited;
  Change;
end;