C# 如何在屏幕上的特定鼠标位置显示窗体?

标签 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);

最佳答案

您的问题是您的第一个调用: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/

相关文章:

c# - 当外键为空时,使用 Lambda 表达式在 List<T> 中排序

ajax - 提交表单后,如何将页面保持在当前位置,以便用户可以看到他们可能犯的错误?

css - 窗口右侧的元素在窗口调整大小时重叠

c# - "sheetwise"如何将 Excel 工作簿保存或导出为 PDF 文件?

c# - 使用 OpenRasta 服务

python - 使用 Django 中的 ManyToManyField 的特定参数在表单中自定义查询

java - Struts2 要求用户上传文件验证

android - 如何正确移动 View ?

html - CSS:始终将页脚放在底部

c# - 事件、委托(delegate)或接口(interface)?