2009-07-27 17 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)以外のものを使用する必要がありますか?これはドットネットコントロールを見つけるだけでしょうか?もしそうなら、私は何を使うべきですか? SetWindowPosでも

、二0はちょうど私がそこに固執ランダムint型だった、私はピジンのような複数のウィンドウでint型のためhWndInsertAfter

何についてのプロセスを使用するかわからないんだけど?

答えて

23

Control.FromHandleとフォーム==ヌルチェックを取り出してください。

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

あなたがSWP_NOSIZEを追加した場合、それはウィンドウのサイズを変更しませんが、まだそれを再配置します:あなたはただ行うことができる必要があります。

あなたは、各プロセスのすべてのウィンドウだけでなく、メインウィンドウを達成するために必要がある場合は、代わりにプロセスのリストを反復処理し、MainWindowHandleを使用してのP/Invoke withEnumWindowsを使用して検討する必要があります。

+0

それはそこになってきたが、いくつかの窓(複数のウィンドウを持っているそれらのプロセスのように思える)は、すべての移動ではありません。 さて、あなたは私の質問の多くに答えて、いつかは、プログラミングのノウハウをいつまでも持ちたいと思っています。 – Matt

+0

Matt:私はその解決策を追加しました。 EnumWindowsは、すべてのトップレベルウィンドウ(MainWindowHandleウィンドウだけでなく)を反復処理します。これにより、必要なものが得られます。 –

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); 
      } 
     } 
} 
} 

関連する問題