2012-07-19 95 views
6

我有兩個窗體,我的主要窗體是Form1,我的輔助窗體按需顯示爲一個對話框Form2。 現在,如果我打電話給Form2,它總是顯示在屏幕的左上角。我第一次以爲我的表格根本不存在,但後來我看到它掛在屏幕的上角。我想在當前鼠標位置顯示我的表單,用戶單擊上下文菜單以顯示模式對話框。 我已經嘗試過不同的事情並搜索代碼示例。但是除了我已經知道的如何以不同方式獲得鼠標的實際位置之外,我沒有發現任何其他的代碼。但無論如何,這個位置總是相對於屏幕,主要形式,控制或任何當前的情境。在這裏我的代碼(桌面定位,我也試過不工作,中心到屏幕中心的形式而已,所以我離開了財產Windows.Default.Position):C#如何在屏幕上的特定鼠標位置顯示錶單?

 Form2 frm2 = new Form2(); 
     frm2.textBox1.Text = listView1.ToString(); 
     frm2.textBox1.Tag = RenameFile; 
     DialogResult dlgres=frm2.ShowDialog(this); 
     frm2.SetDesktopLocation(Cursor.Position.X, Cursor.Position.Y); 

回答

9

你的問題是,您的第一個電話:frm2.ShowDialog(this);,然後致電frm2.SetDesktopLocation,實際上只有在窗體(frm2)已關閉後纔會調用它。

ShowDialog是一個阻塞調用 - 意味着它只有在您調用ShowDialog的窗體關閉時纔會返回。所以你需要一種不同的方法來設置表單的位置。

可能最簡單的方法就是在Form2上創建第二個構造函數(需要定位),該構造函數需要兩個參數,即X和Y座標。

public class Form2 
{ 

    // add this code after the class' default constructor 

    private int desiredStartLocationX; 
    private int desiredStartLocationY; 

    public Form2(int x, int y) 
      : this() 
    { 
     // here store the value for x & y into instance variables 
     this.desiredStartLocationX = x; 
     this.desiredStartLocationY = y; 

     Load += new EventHandler(Form2_Load); 
    } 

    private void Form2_Load(object sender, System.EventArgs e) 
    { 
     this.SetDesktopLocation(desiredStartLocationX, desiredStartLocationY); 
    } 

然後,當你創建來顯示它的形式,使用此構造函數而不是默認的:

Form2 frm2 = new Form2(Cursor.Position.X, Cursor.Position.Y); 
frm2.textBox1.Text = listView1.ToString(); 
frm2.textBox1.Tag = RenameFile; 
DialogResult dlgres=frm2.ShowDialog(this); 

您也可以嘗試在加載處理程序使用this.Move(...)' instead of 'this.SetDesktopLocation

+0

你有沒有試過我的建議?你是否實現了修改過的構造函數,但沒有奏效? – 2012-07-19 02:19:18

+0

@feedwall - 我很高興它爲你工作(並感謝upvote&accept) – 2012-07-19 14:45:11

+0

StartPosition需要設置爲手動 – ehh 2017-06-25 08:58:26

2

您需要的ShowDialog()方法之前調用SetDesktopLocation,就像這樣:

using(Form2 frm2 = new Form2()) 
{ 
    frm2.textBox1.Text = listView1.ToString(); 
    frm2.textBox1.Tag = RenameFile; 
    frm2.SetDesktopLocation(Cursor.Position.X, Cursor.Position.Y); 

    DialogResult dlgres=frm2.ShowDialog(this); 
} 

使用使用statemen的,它的recomanded。祝你好運;)

相關問題