2009-12-22 64 views
1

在我的應用程序中我有一個mainform。當打開按鈕被點擊時,我想顯示第二個(無邊界)形式的文本加載。到目前爲止,我已經有了這個工作。C#WinForms相對於另一個表單定位表單

但我想要的是加載表單相對於mainform居中。我該怎麼做呢?

SOLUTION:

private void tsbOpen_Click(object sender, EventArgs e) 
{ 
    if (_fileDialog.ShowOpenDialog() == DialogResult.OK) 
    { 
     _progress = new frmProgress(); // _progress is a member var 
     backgroundWorker1.RunWorkerAsync("open"); 
     _progress.ShowDialog(this); 

    } 
} 

回答

13

您可以設置中StartPositionCenterParent和傳遞的MainForm作爲所有者

+0

日Thnx,但我表現出一個線程的第二種形式。當我嘗試form.Show(this)時,我得到這個錯誤:'跨線程操作無效:控制'frmProcessBuilder'從一個線程訪問,而不是它創建的線程。' – Martijn 2009-12-22 08:33:42

+0

只適用於'ShowDialog()'。 – Joey 2009-12-22 08:33:52

+0

我無法使用ShowDialog(),因爲直到此對話框關閉,我的代碼纔會停止。這不是我需要的。表單必須在加載完成之前一直顯示。 – Martijn 2009-12-22 08:37:05

-3

獲取主窗體座標及其大小的位置,並獲取子窗體的大小並在其上放置一些簡單的數學。

+0

Thnx,但這不起作用。也許是因爲我從一個線程運行這個代碼? (Backgroundworker_DoWork()) – Martijn 2009-12-22 08:38:20

0

的Martijn試試這個

在方法的開始把一些像這樣的代碼

public sub Bah() 
{ 
    if (me.InvokeRequired) 
    { 
     me.Invoke(new action(Bah)); 
     return 
    } 

    myform.showdialog... 
} 

不知道如果這個代碼編譯爲100%,但你的想法

0

我創建了一個名爲ProcessingRequest的子表單,並在其上放置了一些文本和一個動畫gif。

我有我的主要形式的產權是我的計算子表單應該在的位置。

private Point ProcessingLocation { get { return new Point(this.Location.X + this.Width/2 - new ProcessingRequest().Width/2, this.Location.Y + this.Height/2 - new ProcessingRequest().Height/2); } } 

我有一個類,使一個新的線程來顯示其子形式。

public class ShowProgress 
    { 
     static private System.Drawing.Point point; 
     static private ProcessingRequest p; 
     static public void ShowProgressForm(System.Drawing.Point myPoint) 
     { 
      point = myPoint; 
      Thread t = new Thread(new ThreadStart(ShowProgress.ShowForm)); 
      t.IsBackground = true; 
      t.SetApartmentState(ApartmentState.STA); 
      t.Start(); 
     } 
     static private void ShowForm() 
     { 
      p = new ProcessingRequest(); 
      p.StartPosition = FormStartPosition.Manual; 
      p.Location = point; 
      p.TopMost = true; 
      Application.Run(p); 
     } 

     static public void CloseForm() 
     { 
      p.Invoke(new CloseDelegate(ShowProgress.CloseFormInternal)); 
     } 

     static private void CloseFormInternal() 
     { 
      p.Close(); 
     } 
    } 
    public delegate void CloseDelegate(); 

然後在我的主要形式,我只是把

ShowProgress.ShowProgressForm(ProcessingLocation); 
//heavy processing code goes here or whatever 
ShowProgress.CloseForm(); 

:)