2009-07-27 83 views
19

我有下面的代碼:在C#中使用SetWindowPos移動窗口周圍

namespace WindowMover 
{ 
    using System.Windows.Forms; 

    static class Logic 
    { 
     [DllImport("user32.dll", EntryPoint = "SetWindowPos")] 
     public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); 

     public static void Move() 
     { 
      const short SWP_NOMOVE = 0X2; 
      const short SWP_NOSIZE = 1; 
      const short SWP_NOZORDER = 0X4; 
      const int SWP_SHOWWINDOW = 0x0040; 

      Process[] processes = Process.GetProcesses("."); 
      foreach (var process in processes) 
      { 
       var handle = process.MainWindowHandle; 
       var form = Control.FromHandle(handle); 

       if (form == null) continue; 

       SetWindowPos(handle, 0, 0, 0, form.Bounds.Width, form.Bounds.Height, SWP_NOZORDER | SWP_SHOWWINDOW); 
      } 
     } 
    } 
} 

這應該是我的桌面上每移動窗口0,0(X,Y),並保持相同的尺寸。 我的問題是隻有調用應用程序(內置C#)正在移動。

我應該使用Control.FromHandle(IntPtr)以外的其他東西嗎?這隻會找到dotnet控件嗎?如果是這樣,我應該使用什麼?

此外,第二0 SetWindowPos只是一個隨機INT我堅持在那裏,我不知道用多個窗口例如Pidgin使用什麼INT hWndInsertAfter

怎麼樣的過程?

回答

23

只要拿出你的Control.FromHandle和表單== null檢查。你應該能夠只是做:

IntPtr handle = process.MainWindowHandle; 
if (handle != IntPtr.Zero) 
{ 
    SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); 
} 

如果添加SWP_NOSIZE,也不會改變窗口大小,但仍將重新定位。

如果你想影響所有的窗口,而不僅僅是主窗口,每一個過程中,你可能要考慮使用P/Invoke withEnumWindows而不是通過進程列表迭代和使用MainWindowHandle。

+0

它到達那裏,但一些窗口(好像那些具有多個Windows進程)不是所有運動。 順便說一句,你回答了我的許多問題,我希望有一天我會有儘可能多的編程技巧...... – Matt 2009-07-27 20:35:09

2

玩過這個。看看它是否有幫助。


using System.Windows.Forms; 
using System.Runtime.InteropServices; 
using System.Diagnostics; 


namespace ConsoleTestApp 
{ 
class Program 
{ 
    [DllImport("user32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    static extern bool SetForegroundWindow(IntPtr hWnd); 

    static void Main(string[] args) 
    { 

     Process[] processes = Process.GetProcesses(); 

     foreach (var process in processes) 
     { 
      Console.WriteLine("Process Name: {0} ", process.ProcessName); 

      if (process.ProcessName == "WINWORD") 
      { 
       IntPtr handle = process.MainWindowHandle; 

       bool topMost = SetForegroundWindow(handle); 
      } 
     } 
} 
}