首页  编辑  

Edit&Memo控件的文本得对齐方式

Tags: /超级猛料/VCL/Memo&Edit&Richedit/Edit和Memo/   Date Created:

如何使TEDIT控件中的TEXT显示在控件的中间或下面(一般在上面),

像TLABEL中的LAYOUT至为CENTER一样

var

 Rct: TRect;

begin

 Rct := edit1.ClientRect;

 Inc(Rct.Top, 3);

 sendmessage(edit1.handle, EM_SETRECT, 0, Integer(@Rct));

end;

EM_SETRECT 只对于 Multiline Edit 有效? :-)

 An application sends an EM_SETRECT message to set the formatting rectangle of a

multiline edit control.

换成 Memo 就可以了。

procedure TForm1.Button2Click(Sender: TObject);

var

 Rct: TRect;

begin

 SendMessage(Memo1.Handle, EM_GETRECT, 0, Integer(@Rct));

 Inc(Rct.Top, 5);

 SendMessage(Memo1.Handle, EM_SETRECT, 0, Integer(@Rct));

end;

那也简单, 那些语句前加一句

SetWindowLong(edit.Handle,GWL_STYLE, GetWindowLong(edit.Handle, GWL_STYLE) or ES_MULTILINE);

不过需要多写个OnKeyPress事件过滤掉输入的回车符.

最好自己继承TEdit做个有这功能的控件. 事实上很简单的.

unit JackEdit;

interface

uses

 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

 StdCtrls;

type

 TKeySet = (ksReturn, ksEscape);

 TKeySets = set of TKeySet;

 TJackEdit = class(TEdit)

 private

   { Private declarations }

   FAlignment: TAlignment;

   FKeys: TKeySets;

   procedure SetAlignment(value: TAlignment);

 protected

   { Protected declarations }

   procedure CreateParams(var Params: TCreateParams); override;

   procedure KeyPress(var Key: Char); override;

 public

   { Public declarations }

   constructor Create(AOwner: TComponent); override;

   destructor Destroy; override;

 published

   { Published declarations }

   property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;

   property Keys: TKeySets read FKeys write FKeys;

 end;

procedure Register;

implementation

procedure TJackEdit.SetAlignment(value: TAlignment);

begin

 if value <> FAlignment then

 begin

   FAlignment := value;

   RecreateWnd;

 end;

end;

procedure TJackEdit.KeyPress(var Key: Char);

begin

 if ksReturn in Keys then

 begin

   if Key = Chr(Vk_Return) then

   begin

     Key := Chr(0);

     (Owner as TControl).Perform(wm_NextDlgCtl,0,0);

   end;

 end;

 if ksEscape in Keys then

 begin

   if Key = Chr(Vk_Escape) then

   begin

     Key := Chr(0);

    (Owner as TControl).Perform(wm_NextDlgCtl,1,0);

   end;

 end;

 inherited KeyPress(Key);

end;

procedure TJackEdit.CreateParams(var Params: TCreateParams);

begin

 inherited CreateParams(Params);

 case Alignment of

   taLeftJustify  : Params.Style := Params.Style or (ES_LEFT or Es_MULTILINE);

   taRightJustify : Params.Style := Params.Style or (ES_RIGHT or ES_MULTILINE);

   taCenter       : Params.Style := Params.Style or (ES_CENTER or Es_MULTILINE);

 end;

end;

constructor TJackEdit.Create(AOwner: TComponent);

begin

 inherited Create(AOwner);

 FAlignment := taLeftJustify;

end;

destructor TJackEdit.Destroy;

begin

 inherited Destroy;

end;

procedure Register;

begin

 RegisterComponents('Jack', [TJackEdit]);

end;

end.