问题
Using delphi and rich edit, I need to replicate something along the lines of this very editor I'm writing in, when you select a text and press on the Bold button, the text remains selected instead of unselecting and losing focus.
How can I achieve this?
Thank you.
回答1:
OK, now I think I see the issue. You have a TRichEdit
and a TButton
. Then you do something like
procedure TForm1.Button1Click(Sender: TObject);
begin
with RichEdit1.SelAttributes do
Style := Style + [fsBold];
end;
and you are annoyed by the fact that the Rich Edit control loses its focus when you click Button1
. Normally you use a TToolButton
in a TToolbar
as the 'bold' button. This will not make the editor lose its focus, because a TToolButton
is not a windowed control.
If you do not wish to use a TToolBar
(or any equivalent control), simply use a TSpeedButton
instead of a TButton
.
The normal way of doing this, however, is to use a TActionList
. Drop such a control on your form, and then add a new action, call it ActnBold
or something. Set the caption to 'Bold'
, the hint to 'Make the selection bold.'
, add the shortcut Ctrl+B
, and write
with RichEdit1.SelAttributes do
Style := Style + [fsBold];
in its OnExecute
event. Then you can associate this action to any button, speed button, toolbar button, menu item, ..., simply by setting the control's Action
property to ActnBold
.
If you really, really want to use a windowed control, such as a TButton
, then you can do
procedure TForm1.Button1Click(Sender: TObject);
begin
with RichEdit1.SelAttributes do
Style := Style + [fsBold];
RichEdit1.SetFocus;
end;
but it isn't beautiful (IMHO).
来源:https://stackoverflow.com/questions/5707638/is-it-possible-to-avoid-a-trichedit-losing-its-focus-when-clicking-a-button-e-g