Как получить окно приложения наверх - PullRequest
0 голосов
/ 12 января 2012

Используя C #, я хотел бы вывести определенное окно в верхнюю часть экрана, и после этого я запустил макрос на нем.

Tried,

[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);
[DllImportAttribute("User32.dll")]
private static extern int SetForegroundWindow(int hWnd);

ипосле,

        string main_title;
        Process[] processlist = Process.GetProcesses();
        foreach (Process theprocess in processlist)
        {
            if (theprocess.ProcessName.StartsWith(name))
            {
                main_title = theprocess.MainWindowTitle;
                hWnd = theprocess.Handle.ToInt32();
                break;
            }
            hWnd = FindWindow(null, main_title);
            if (hWnd > 0)
            {
                SetForegroundWindow(hWnd);
            }

и получил ошибку,

имя типа или пространства имен 'DllImportAttribute' не может быть найдено

используется,

using System.Runtime;

и теперь я не могу распознать hWnd в моем коде, хотя все они находятся в одном и том же пространстве имен и частичном классе.

После испытаний

   IntPtr hWnd;
    Process[] processlist = Process.GetProcesses();
    foreach (Process theprocess in processlist)
    {
        if (theprocess.ProcessName.StartsWith("msnmsgr"))
        {
            main_title = theprocess.MainWindowTitle;
            hWnd = theprocess.MainWindowHandle;
            SetForegroundWindow(hWnd);

        }
    }

это похоже на передний план окна,по крайней мере, в соответствии с порядком alt-tab, и приложения выглядят как выбранные на панели инструментов, но они не становятся видимыми.

1 Ответ

1 голос
/ 12 января 2012

Попробуйте вместо этого использовать DllImport, например:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.DLL")]
public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);

Определить hWnd как:

IntPtr hWnd;

В вашем задании выполните:

hWnd = theProcess.MainWindowHandle;  // or use your theProcess.Handle

Кроме того, этот разрыв в операторе if не будет устанавливать окно на передний план, если оно его найдет. Вам нужно переделать этот сегмент кода в что-то вроде:

if (theprocess.ProcessName.StartsWith(name))
{
    main_title = theprocess.MainWindowTitle;
    hWnd = theProcess.MainWindowHandle;
}
else
    hWnd = FindWindow(null, main_title);

if (hWnd != null && !hWnd.Equals(IntPtr.Zero))
{
    SetForegroundWindow(hWnd);
    // may want to put your break here
}

Класс окна

Win32 - это просто класс, содержащий все описанные выше DllImport, поскольку я использую их в нескольких дочерних классах Win32.

public class Window : Win32
{
    public IntPtr Handle;

    public Window(IntPtr handle)
    {
        Handle = handle;
    }

    public bool Visible
    {
        get { return IsWindowVisible(Handle); }
        set
        {
            ShowWindow(Handle, value ? ShowWindowConsts.SW_SHOW :
                ShowWindowConsts.SW_HIDE);
        }
    }

    public void Show() 
    { 
        Visible = true;
        SetForegroundWindow(Handle);
        /*
        try { SwitchToThisWindow(Handle, false); } // this is deprecated - may throw on new window platform someday
        catch { SetForegroundWindow(Handle); } // 
        */
    }

    public void Hide() { Visible = false; }
}

Класс ShowWindowConsts

namespace Win32
{
    public class ShowWindowConsts
    {
        // Reference: http://msdn.microsoft.com/en-us/library/ms633548(VS.85).aspx

        /// <summary>
        /// Minimizes a window, even if the thread that owns the window is not responding. 
        /// This flag should only be used when minimizing windows from a different thread.
        /// </summary>
        public const int SW_FORCEMINIMIZE = 11;

        /// <summary>
        /// Hides the window and activates another window.
        /// </summary>
        public const int SW_HIDE = 0;

        /// <summary>
        /// Maximizes the specified window.
        /// </summary>
        public const int SW_MAXIMIZE = 3;

        /// <summary>
        /// Minimizes the specified window and activates the next top-level window in the Z order.
        /// </summary>
        public const int SW_MINIMIZE = 6;

        /// <summary>
        /// Activates and displays the window. 
        /// If the window is minimized or maximized, the system restores it to 
        /// its original size and position. 
        /// An application should specify this flag when restoring a minimized window.
        /// </summary>
        public const int SW_RESTORE = 9;

        /// <summary>
        /// Activates the window and displays it in its current size and position.
        /// </summary>
        public const int SW_SHOW = 5;

        /// <summary>
        /// Sets the show state based on the public const long SW_ value specified in 
        /// the STARTUPINFO structure passed to the CreateProcess function by 
        /// the program that started the application.
        /// </summary>
        public const int SW_SHOWDEFAULT = 10;

        /// <summary>
        /// Activates the window and displays it as a maximized window.
        /// </summary>
        public const int SW_SHOWMAXIMIZED = 3;

        /// <summary>
        /// Activates the window and displays it as a minimized window.
        /// </summary>
        public const int SW_SHOWMINIMIZED = 2;

        /// <summary>
        /// Displays the window as a minimized window. 
        /// This value is similar to public const long SW_SHOWMINIMIZED, 
        /// except the window is not activated.
        /// </summary>
        public const int SW_SHOWMINNOACTIVE = 7;

        /// <summary>
        /// Displays the window in its current size and position. 
        /// This value is similar to public const long SW_SHOW, except that the window is not activated.
        /// </summary>
        public const int SW_SHOWNA = 8;

        /// <summary>
        /// Displays a window in its most recent size and position. 
        /// This value is similar to public const long SW_SHOWNORMAL, 
        /// except that the window is not activated.
        /// </summary>
        public const int SW_SHOWNOACTIVATE = 4;

        public const int SW_SHOWNORMAL = 1;
    }
}

Таким образом, ваш код станет:

if (theprocess.ProcessName.StartsWith(name))
{
    main_title = theprocess.MainWindowTitle;
    hWnd = theProcess.MainWindowHandle;
}
else
    hWnd = FindWindow(null, main_title);

if (hWnd != null && !hWnd.Equals(IntPtr.Zero))
{
    new Window(hWnd).Show();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...