1. 程式人生 > >Delphi7如何實現讓Tedit顯示文字垂直居中(上下居中)

Delphi7如何實現讓Tedit顯示文字垂直居中(上下居中)

nbsp messages dialog nco windows util proc keypress inter

通過下面的組件,可以在輸入文字的時候自動垂直居中
直接把下面代碼保存到Unit1.pas即可
------------------------------------------

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TEdit = class(StdCtrls.TEdit)
  protected
    procedure CreateParams(var Params: TCreateParams); override
; procedure KeyPress(var Key: Char); override; procedure WMSize(var msg: TWMSize);message WM_SIZE; procedure SetParent(AParent: TWinControl);override; procedure SetCenter; end; TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure FormCreate(Sender: TObject);
private { Private declarations } public { Public declarations } Edt: TEdit; end; var Form1: TForm1; implementation {$R *.dfm} { TEdit } procedure TForm1.FormCreate(Sender: TObject); begin Edt := TEdit.Create(self); Edt.Parent := self; Edt.AutoSize := False; Edt.Height :
= 50; end; procedure TEdit.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := Params.Style or ES_MULTILINE; end; procedure TEdit.KeyPress(var Key: Char); begin inherited; if Key = #13 then key := #0; end; procedure TEdit.WMSize(var msg: TWMSize); begin inherited; SetCenter; end; procedure TEdit.SetParent(AParent: TWinControl); begin inherited; if Parent <> nil then begin SetCenter; end; end; procedure TEdit.SetCenter; var DC: HDC; SaveFont: HFont; Sin: Integer; SysMetrics, Metrics: TTextMetric; Rct: TRect; begin DC := GetDC(0); GetTextMetrics(DC, SysMetrics); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); ReleaseDC(0, DC); if Ctl3D then Sin := 8 else Sin := 6; Rct := ClientRect; Sin := Height - Metrics.tmHeight - Sin; Rct.Top := Sin div 2; SendMessage(Handle, EM_SETRECT, 0, Integer(@Rct)); end; end.

當這個保存成unit1.pas 後,然後通過delphi組件安裝功能來安裝組件,具體安裝方法可以到網上查方法

Delphi7如何實現讓Tedit顯示文字垂直居中(上下居中)