如何从当前鼠标光标位置开始表单的形式?

时间:2014-01-22 03:19:08

标签: c# winforms

我有这一行:

StartPosition = FormStartPosition.Manual;

在我的程序中,每次我点击一个显示新表单的按钮。 但它不好我想要每次鼠标光标所在的表格位置。 我该怎么办?

3 个答案:

答案 0 :(得分:4)

将此文件放在form_Load()事件

var _point = new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y);
Top = _point.Y;
Left = _point.X;

答案 1 :(得分:1)

我会使用构造函数重载,但除此之外它与John Woo的回答相同。

public Form1()
{
    InitializeComponent();
    // mandatory, could be set in the designer
    StartPosition = FormStartPosition.Manual;
}

public Form1(int x, int y):
    this()
{
    this.Left = x;
    this.Top = y;
}

public Form1(Point location):
    this()
{
    this.Location = location;
}

并使用另一种形式的事件(由于this设置父级):

var form = new Form1(Cursor.Position);
form.ShowDialog(this);

答案 2 :(得分:0)

        var form = new Form1();
        form.StartPosition = FormStartPosition.Manual;
        form.Left = Cursor.Position.X;
        form.Top = Cursor.Position.Y;

        var width= Screen.PrimaryScreen.Bounds.Width;
        var height = Screen.PrimaryScreen.Bounds.Width;

        if (form.Left + form.Width > width)
        {
            form.Left = width - form.Width;
        }

        if (form.Top+form.Height>height)
        {
            form.Top = height - form.Height;
        }