How to get the position of a Windows Form on the screen?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-12 13:43:30

问题


I am coding a WinForms application in Visual Studio C# 2010 and I want to find out the location of the upper left corner of the WinForm window (the starting location of the window).

How can I do that?


回答1:


If you are accessing it from within the form itself then you can write

int windowHeight = this.Height;
int windowWidth = this.Width;

to get the width and height of the window. And

int windowTop = this.Top; 
int windowLeft = this.Left;

To get the screen position.

Otherwise, if you launch the form and are accessing it from another form

int w, h, t, l;
using (Form form = new Form())
{
    form.Show();
    w = form.Width;
    h = form.Height;
    t = form.Top;
    l = form.Left;
}

I hope this helps.




回答2:


Form.Location.X and Form.Location.Y will give you the X and Y coordinates of the top left corner.




回答3:


Use Form.Bounds.Top to get the "Y" coordinate and Form.Bounds.Left to get the "X" coordinate




回答4:


I had a similar case where for my Form2 i needed the screen location of Form1. i Solved it by passing the screen locationof form1 to form2 through its constructor :

//Form1

 Point Form1Location;
        Form1Location = this.Location;
        Form2 myform2 = new Form2(Form1Location);
        myform2.Show();

//Form2

 Point Form1Loc;
    public Form2(Point Form1LocationRef)
    {
        Form1Loc = Form1LocationRef;
        InitializeComponent();

    }



回答5:


check this: Form.DesktopLocation Property

        int left = this.DesktopLocation.X;
        int top = this.DesktopLocation.Y;



回答6:


Also a combination of the Left and Top properties (e.g. this.Top from within the form)



来源:https://stackoverflow.com/questions/14526101/how-to-get-the-position-of-a-windows-form-on-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!