Using SetWindowPos in C# to move windows around

前端 未结 2 1457
春和景丽
春和景丽 2020-12-03 02:53

I have the code below:

namespace WindowMover
{
    using System.Windows.Forms;

    static class Logic
    {
        [DllImport(\"user32.dll\", EntryPoint =          


        
相关标签:
2条回答
  • 2020-12-03 03:41

    Just take out your Control.FromHandle and the form == null check. You should be able to just do:

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

    If you add SWP_NOSIZE, it will not resize the window, but will still reposition it.

    If you want to effect all windows, not just the main window, of each process, you might want to consider using P/Invoke with EnumWindows instead of iterating through the Process list and using MainWindowHandle.

    0 讨论(0)
  • 2020-12-03 03:44

    Played with this. See if it helps.


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

    0 讨论(0)
提交回复
热议问题