我有两个表单,主表单是 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);
最佳答案
您的问题是您的第一个调用: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(...)' 而不是 'this.SetDesktopLocation
。
关于C# 如何在屏幕上的特定鼠标位置显示窗体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11552667/