fee*_*all 8 c# forms position show mouse-position
我有两个表单,我的主要表单是Form1,我的辅助表单是按需显示的,因为对话框是Form2.现在,如果我调用Form2,它将始终显示在屏幕的左上角.我第一次认为我的表格根本不存在,但后来我看到它悬挂在屏幕的上方.我想在当前鼠标位置显示我的表单,用户单击上下文菜单以显示模式对话框.我已经尝试过不同的东西并搜索代码示例.但是我发现除了数以千计的不同代码之外什么也没有找到如何以我已经知道的不同方式获得实际的鼠标位置.但无论如何,这个位置总是相对于屏幕,主要形式,控制或任何当前上下文.在这里我的代码(我也尝试过的桌面定位不起作用,中心到屏幕只是表单的中心,所以我把属性留给了Windows.Default.Position):
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);
Run Code Online (Sandbox Code Playgroud)
Mik*_*scu 10
你的问题是你的第一次调用: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);
}
Run Code Online (Sandbox Code Playgroud)
然后,当您创建表单以显示它时,请使用此构造函数而不是默认构造函数:
Form2 frm2 = new Form2(Cursor.Position.X, Cursor.Position.Y);
frm2.textBox1.Text = listView1.ToString();
frm2.textBox1.Tag = RenameFile;
DialogResult dlgres=frm2.ShowDialog(this);
Run Code Online (Sandbox Code Playgroud)
您也可以尝试this.Move(...)' instead of 'this.SetDesktopLocation在Load处理程序中使用.