2012-03-12 128 views
5

我想知道获得process'es窗口位置的方式。我一直在网上寻找,但没有结果。谢谢:)如何获取窗口的位置?

Process[] processes = Process.GetProcessesByName("notepad"); 
Process lol = processes[0]; 

IntPtr p = lol.MainWindowHandle; 
+2

Dup的 - http://stackoverflow.com/questions/1364440/how-to-get-and-set-window-position-另一种应用在c-sharp中 – 2012-03-12 14:26:48

+0

你想用它做什么? [从他的窗口杀毒退出:)] – 2012-03-12 15:00:37

+0

笑,是用于获取窗口的位置,只能使用你能想到的? – Patryk 2012-03-12 15:16:25

回答

8

试试这个:

[DllImport("user32.dll", CharSet = CharSet.Auto)] 
public static extern IntPtr FindWindow(string strClassName, string strWindowName); 

[DllImport("user32.dll")] 
public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle); 

public struct Rect { 
    public int Left { get; set; } 
    public int Top { get; set; } 
    public int Right { get; set; } 
    public int Bottom { get; set; } 
} 

Process[] processes = Process.GetProcessesByName("notepad"); 
Process lol = processes[0]; 
IntPtr ptr = lol.MainWindowHandle; 
Rect NotepadRect = new Rect(); 
GetWindowRect(ptr, ref NotepadRect); 
+0

作品,谢谢:) – Patryk 2012-03-12 15:27:55

+0

它将工作。好。但是当记事本已经缩小到任务栏时,这段代码将不起作用。你应该检查一下。 (另外,我建议使用try-catch来避免“notepad is not running”错误) – 2012-04-25 07:24:10

+7

Rect成员var的顺序错误。它应该是左,上,右下。否则,你会得到不正确的值。 – Nick 2013-11-06 04:06:30

1
using System.Runtime.InteropServices; 
using System.Diagnostics; 


public class GetNotePadLocation 
{ 

    [DllImport("user32.dll", CharSet = CharSet.Auto)] 
    public static extern IntPtr FindWindow(string strClassName, string strWindowName); 

    [DllImport("user32.dll")] 
    public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle); 

    public struct Rect 
    { 
     public int Left { get; set; } 
     public int Top { get; set; } 
     public int Right { get; set; } 
     public int Bottom { get; set; } 
    } 
    public static void NotePadLocation() 
    { 
     Process[] processes = Process.GetProcessesByName("notepad"); 
     Process lol = processes[0]; 
     IntPtr ptr = lol.MainWindowHandle; 
     Rect NotepadRect = new Rect(); 
     GetWindowRect(ptr, ref NotepadRect); 
    } 
} 
+0

我想我已经找到了缺失的部分,那里有在结构部分顺序错误;我已经修复它... 但我实际上不知道如何获得所有打开的记事本窗口的这些属性以及如何获得活动的维度 感谢您的帮助... – hazem 2013-09-07 12:06:25