如何獲取並設置使用C#的另一個應用程序的位置?如何獲取並設置C#中另一個應用程序的窗口位置?
例如,我想得到記事本的左上角座標(假設它漂浮在某處100,400處)以及此窗口的位置爲0,0。
實現此目的的最簡單方法是什麼?
如何獲取並設置使用C#的另一個應用程序的位置?如何獲取並設置C#中另一個應用程序的窗口位置?
例如,我想得到記事本的左上角座標(假設它漂浮在某處100,400處)以及此窗口的位置爲0,0。
實現此目的的最簡單方法是什麼?
我實際上是爲這類事情寫了一個開源的DLL。 Download Here
這將允許您查找,枚舉,調整大小,重新定位或做任何你想要的其他應用程序窗口及其控件。 還有增加的功能來讀取和寫入窗口/控件的值/文本,並在它們上點擊事件。它基本上是用來進行屏幕抓取 - 但所有的源代碼都包含在內,所以你想用窗口做的所有事情都包括在內。
嘗試使用FindWindow(signature)來獲取目標窗口的HWND。然後你可以使用SetWindowPos(signature)來移動它。
您將需要使用som P/Invoke interop來實現此目的。基本思想是先找到窗口(例如,使用EnumWindows function),然後用GetWindowRect獲得窗口位置。
David's helpful answer提供了關鍵的指針和有用的鏈接。
把他們在實現中問題的示例場景一個自包含的例子來使用,通過P/Invoke的使用Windows API(System.Windows.Forms
是不參與):
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);
}
}
}
感謝資源! :)這非常有用。 – 2011-01-06 00:45:22
@DataDink,你會把這個庫移動到GitHub嗎? – Theraot 2012-10-12 04:56:48
找到項目名稱:WindowScrape。目前可在此處找到:http://code.google.com/p/lol-mastery-tool/source/browse/LOL+Mastery+Tool/WindowScrape.dll?r=b88d6a538d88e052a88c69ffb70aaa09fc4a735e可用來源:https:// bitbucket .org/crwilcox/turbo-click/commits/89a687df7511490effb22ad3fc3e48fc9ab8c47a#chg-WindowScrape/ReadMe.txt它的自述文件中的一些內容,用於將來的搜索'HwndObject類將一些窗口句柄的功能封裝到UI對象中.' – mbrownnyc 2013-10-20 23:23:54