TSaveDialog的位置

时间:2009-03-18 08:38:38

标签: delphi

TSaveDialog的默认位置是屏幕的中心。如何设置TSaveDialog窗口的位置?我想要这样的东西:

SaveDialog1.top := topValue;
SaveDialog1.left := leftValue;
if (SaveDialog1.execute(self.handle)) then begin
  ...
end;

2 个答案:

答案 0 :(得分:2)

我在此page找到了此示例,但我修改了它以使用退出TSaveDialog而不是创建新类。

type
 TSaveDialog = class(Dialogs.TSaveDialog)
   protected
      fTop: integer;
      fLeft: integer;
      procedure WndProc(var Message: TMessage); override;
   public
      property top: integer read fTop write fTop;
      property left: integer read fLeft write fLeft;
   end;

type
  TForm1 = class(TForm)
    dlgSave1: TSaveDialog;
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;


var
  Form1: TForm1;

implementation

{$R *.dfm}
uses
  CommDlg;

procedure TForm1.btn1Click(Sender: TObject);
begin
  dlgSave1.left := 20;
  dlgSave1.top := 100;
   if dlgSave1.Execute then
   // do your work here
end;

{ TMySaveDialog }

procedure TSaveDialog.WndProc(var Message: TMessage);
begin
  inherited WndProc(Message);
  if (Message.Msg = WM_NOTIFY) then
      case (POFNotify(Message.LParam)^.hdr.code) of
           CDN_INITDONE: SetWindowPos(POFNotify(Message.LParam)^.hdr.hwndFrom, 0, fLeft, fTop, 0, 0, SWP_NOSIZE);
      end;
end;

答案 1 :(得分:2)

GetSaveFileName API函数,即TSaveDialog是一个包装器形式,它没有提供任何方法来控制对话框的位置,所以你需要拦截一个早期的消息到对话框并调整位置,就像你见过的其他解决方案一样。

您希望对话框在表单上居中,因此为对话框提供TopLeft属性的解决方案将无法正常工作,因为它们不会将窗口的大小设置为帐户,他们还要求您在每次致电Execute之前计算新坐标。

这是一个不同的想法。它仍然需要覆盖WndProc

type
  TCenterSaveDialog = class(TSaveDialog)
  private
    FCenterForm: TCustomForm;
  protected
    procedure WndProc(var Message: TMessage); override;
  public
    // When this property is assigned, the dialog will center
    // itself over the given form each time the dialog appears.
    property CenterForm: TCustomForm read FCenterForm write FCenterForm;
  end;

procedure TCenterSaveDialog.WndProc(var Message: TMessage);
var
  lpOfNotify: POFNotify;
  FormRect, DialogRect: TRect;
  NewLeft, NewTop: Integer;
begin
  inherited;
  if (Message.Msg = wm_Notify) and Assigned(CenterForm) then begin
    lpOfNotify := POFNotify(Message.LParam);
    if lpOfNotify.hdr.code = cdn_InitDone then begin
      GetWindowRect(CenterForm.Handle, FormRect);
      GetWindowRect(lpOfNotify.hdr.hwndFrom, DialogRect);
      NewLeft := FormRect.Left
        + (FormRect.Right - FormRect.Left) div 2
        - (DialogRect.Right - DialogRect.Left) div 2;
      NewTop := FormRect.Top
        + (FormRect.Bottom - FormRect.Top) div 2
        - (DialogRect.Bottom - DialogRect.Top) div 2;
      SetWindowPos(lpOfNotify.hdr.hwndFrom, 0,
        NewLeft, NewTop, 0, 0,
        swp_NoActivate or swp_NoOwnerZOrder or swp_NoSize or swp_NoZOrder);
    end;
  end;
end;

另请参阅:cdn_InitDone