I have a form that is being opened by another form.
I set the Position to be poOwnerFormCenter, so that the new form is opened where the original was
However, when I move this new form and then go back to the original, its shown where it wa开发者_JAVA技巧s when I first opened the new form, not where I closed it
How would I fix this?
Thanks!
I'm a bit confused by your question so I'll clarify what I'm try to solve here!...
I think what you're trying to do is
When Form2 Opens, it is positioned centrally to Form1 and Form1 is hidden.
When Form2 Closes, Form1 is shown (exactly where it was hidden).
I think you want to do is have Form1 Show where Form2 was closed.
So I'm guessing that you have some code like...
procedure TForm1.ButtonClick(Sender: TObject);
begin
Form2.ShowModal;
end;
and you were expecting Form2 to update form1's position because you set Form2's position to poOwnerFormCenter
Well if I guessed all that correctly then all you need to do to update Form1's position when Form2 closes is
procedure TForm1.ButtonClick(Sender: TObject);
begin
Form2.ShowModal;
Left := Form2.Left;
Top := Form2.Top;
end;
The problem is that you are reusing the same instance of the modal form. Setting the position only works the first time you show the form. You have to options here:
Option 1
You can destroy the modal form every time it closes. One of the ways of doing that is having this line on the OnClose
event of the form:
Action = caFree;
Of course, that means you have to recreate the modal form from the caller every time as well.
Option 2
You have to manually set the modal form's position on the OnShow
event.
Use the option which best suits you.
This is (I guess) because you recreate the form every time you display it. That is, you do
with TForm2.Create(nil) do
try
ShowModal;
finally
Free;
end;
Because you create a new instance of the TForm2
class every time you show it, and destroy it when the form has closed, the position changes; indeed, the new TForm2
object cannot possibly remember the position of any previous TForm2
object. They are two different objects (yes, same class, but that doesn't matter)!
The simplest solution is to add the TForm2
to the 'auto-create forms' list in the Project Options. It is there by default, but if you create it manually (as I think you do, and as in the code snippet above), you should have removed it from the list of forms that are automatically created...
Then you make sure that Unit1
uses Unit2
, so that you can access the global Form2
variable in Unit2
from Form1
that resides in Unit1
. While editing Unit1
, press Alt+F11 to do this.
Then you can just show Form2
by doing
Form2.ShowModal;
The first time it is shown, it will respect its Position
parameter, and position itself above its owner form. But then it will remember its position, so the second time you display it, it will be right where it closed the first time.
精彩评论