2009-09-01 6 views
17

C#を使用して別のアプリケーションの位置を取得および設定するにはどうすればよいですか?C#で別のアプリケーションのウィンドウ位置を取得および設定する方法

たとえば、メモ帳の左上の座標を取得したいとします(100,400のどこかに浮動小数点があるとします)。このウィンドウの位置を0,0にします。

これを達成する最も簡単な方法は何ですか?

答えて

26

私は実際にこの種のもののためだけにオープンソースのDLLを書いています。 Download Here

これにより、他のアプリケーションウィンドウとそのコントロールに必要なものを見つけたり、列挙したり、サイズを変更したり、位置を変更したりできます。 また、ウィンドウ/コントロールの値/テキストを読み書きする機能と、その上でクリックイベントを行う機能が追加されました。基本的にはスクリーンスクレイピングを行うように書かれていますが、すべてのソースコードが含まれているので、ウィンドウでやりたいことはすべてそこに含まれています。

+1

感謝ソース! :)それは非常に便利です。 –

+1

@DataDink、このライブラリをGitHubに移動しますか? – Theraot

+0

にプロジェクト名WindowScrapeがあります。現在入手可能です:http://code.google.com/p/lol-mastery-tool/source/browse/LOL+Mastery+Tool/WindowScrape.dll?r=b88d6a538d88e052a88c69ffb70aaa09fc4a735eソースは入手可能です:https:// bitbucket .org/crwilcox/turbo-click /コミット/ 89a687df7511490effb22ad3fc3e48fc9ab8c47a#chg-WindowScrape/ReadMe.txt将来の検索のためのreadmeの一部の内容 'HwndObjectクラスは、UIオブジェクトのウィンドウハンドルの周りにいくつかの機能をカプセル化します。 ' – mbrownnyc

4

これを達成するには、som P/Invoke interopを使用する必要があります。基本的な考え方は、ウィンドウを最初に見つけ出すことです(例えば、EnumWindows functionを使用して)、次にGetWindowRectでウィンドウの位置を取得します。

3

David's helpful answerは、重要なポインタと役立つリンクを提供します。 P /呼び出し(System.Windows.Forms関与ではない)を経由して、WindowsのAPIを使用して、問題のサンプルシナリオを実装して自己完結型の例で使用するためにそれらを置くために

:用

using System; 
using System.Runtime.InteropServices; // For the P/Invoke signatures. 

public static class PositionWindowDemo 
{ 

    // P/Invoke declarations. 

    [DllImport("user32.dll", SetLastError = true)] 
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

    [DllImport("user32.dll", SetLastError = true)] 
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); 

    const uint SWP_NOSIZE = 0x0001; 
    const uint SWP_NOZORDER = 0x0004; 

    public static void Main() 
    { 
     // Find (the first-in-Z-order) Notepad window. 
     IntPtr hWnd = FindWindow("Notepad", null); 

     // If found, position it. 
     if (hWnd != IntPtr.Zero) 
     { 
      // Move the window to (0,0) without changing its size or position 
      // in the Z order. 
      SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER); 
     } 
    } 

}