web-dev-qa-db-fra.com

Maximiser la fenêtre WPF sur l'écran actuel

J'ai une application wpf sans fenêtre, chaque fois que je règle l'état de la fenêtre sur maximisé, il le maximise sur l'affichage principal.

Ce que je voudrais faire, c’est d’optimiser l’affichage de l’application en cours.

Donc, une idée de comment je ferais ça?

Mon code pour le moment est juste

private void titleBarThumb_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Normal)
            {
                this.WindowState = System.Windows.WindowState.Maximized;
            }
            else
            {
                this.WindowState = System.Windows.WindowState.Normal;
            }
        }
41
electricsheep

J'ai inclus cette ligne sur mon constructeur MainWindow (premier contrôle):

Application.Current.MainWindow.WindowState = WindowState.Maximized;
37
Web Developer

En raison de la barre des tâches, vous devez utiliser la taille de la zone de travail de l'utilisateur:

this.Width=SystemParameters.WorkArea.Width;
this.Height=SystemParameters.WorkArea.Height;

Vous pouvez utiliser le constructeur de cette vue

11
Navid Rahmani

Une question avec 7 votes positifs mérite le réponse correcte. :RÉ

Utilisez cette fenêtre au lieu de la fenêtre normale et Maxmize/Minimize/normalize se chargera de lui même.

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

public partial class MyWindow : Window
{
    public MyWindow ()
    {
        this.InitializeComponent();

        this.SourceInitialized += this.OnSourceInitialized;
    }

    #endregion

    #region Methods

    private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case 0x0024:
                WmGetMinMaxInfo(hwnd, lParam);
                handled = true;
                break;
        }
        return (IntPtr)0;
    }

    private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
    {
        var mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

        // Adjust the maximized size and position to fit the work area of the correct monitor
        IntPtr monitor = MonitorFromWindow(hwnd, (int)MonitorFromWindowFlags.MONITOR_DEFAULTTONEAREST);

        if (monitor != IntPtr.Zero)
        {
            var monitorInfo = new MONITORINFO();
            GetMonitorInfo(monitor, monitorInfo);
            RECT rcWorkArea = monitorInfo.rcWork;
            RECT rcMonitorArea = monitorInfo.rcMonitor;
            mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.Left - rcMonitorArea.Left);
            mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.Top - rcMonitorArea.Top);
            mmi.ptMaxSize.x = Math.Abs(rcWorkArea.Right - rcWorkArea.Left);
            mmi.ptMaxSize.y = Math.Abs(rcWorkArea.Bottom - rcWorkArea.Top);
        }

        Marshal.StructureToPtr(mmi, lParam, true);
    }

    private void OnSourceInitialized(object sender, EventArgs e)
    {
        var window = sender as Window;

        if (window != null)
        {
            IntPtr handle = (new WindowInteropHelper(window)).Handle;
            HwndSource.FromHwnd(handle).AddHook(WindowProc);
        }
    }
}

Importations et déclarations de DLL

[StructLayout(LayoutKind.Sequential)]
public struct MINMAXINFO
{
    public POINT ptReserved;

    public POINT ptMaxSize;

    public POINT ptMaxPosition;

    public POINT ptMinTrackSize;

    public POINT ptMaxTrackSize;
} ;

public enum MonitorFromWindowFlags
{
    MONITOR_DEFAULTTONEAREST = 0x00000002
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MONITORINFO
{
    public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));

    public RECT rcMonitor;

    public RECT rcWork;

    public int dwFlags;
}

[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct RECT
{
    public int Left;

    public int Top;

    public int Right;

    public int Bottom;

    public static readonly RECT Empty;

    public int Width
    {
        get
        {
            return Math.Abs(this.Right - this.Left);
        } // Abs needed for BIDI OS
    }

    public int Height
    {
        get
        {
            return this.Bottom - this.Top;
        }
    }

    public RECT(int left, int top, int right, int bottom)
    {
        this.Left = left;
        this.Top = top;
        this.Right = right;
        this.Bottom = bottom;
    }

    public RECT(RECT rcSrc)
    {
        this.Left = rcSrc.Left;
        this.Top = rcSrc.Top;
        this.Right = rcSrc.Right;
        this.Bottom = rcSrc.Bottom;
    }

    public bool IsEmpty
    {
        get
        {
            // BUGBUG : On Bidi OS (hebrew arabic) left > right
            return this.Left >= this.Right || this.Top >= this.Bottom;
        }
    }

    public override string ToString()
    {
        if (this == Empty)
        {
            return "RECT {Empty}";
        }
        return "RECT { left : " + this.Left + " / top : " + this.Top + " / right : " + this.Right + " / bottom : " +
               this.Bottom + " }";
    }

    public override bool Equals(object obj)
    {
        if (!(obj is RECT))
        {
            return false;
        }
        return (this == (RECT)obj);
    }

    public override int GetHashCode()
    {
        return this.Left.GetHashCode() + this.Top.GetHashCode() + this.Right.GetHashCode() +
               this.Bottom.GetHashCode();
    }

    public static bool operator ==(RECT rect1, RECT rect2)
    {
        return (rect1.Left == rect2.Left && rect1.Top == rect2.Top && rect1.Right == rect2.Right &&
                rect1.Bottom == rect2.Bottom);
    }

    public static bool operator !=(RECT rect1, RECT rect2)
    {
        return !(rect1 == rect2);
    }
}
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);
4
NVM

Je ne suis pas sûr si cela est répondu encore. J'ai créé un exemple d'application avec le 

WindowStyle = WindowStyle.None;

J'ai créé un bouton et le gestionnaire de clics l'a fait-

WindowState = WindowState.Maximized

J'ai branché le gestionnaire MouseLeftButtonDown pour que la fenêtre glisse

this.MouseLeftButtonDown += new(MainWindow_MouseLeftButtonDown);

private void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   DragMove();
}

Lorsque j'ai fait glisser ma fenêtre sur mon deuxième moniteur et que j'ai cliqué sur le bouton Agrandir, la fenêtre a été agrandie, pas dans la fenêtre de démarrage. J'utilisais VS2010 et .NET 4. Faites-moi savoir si cela vous aidera. 

4
thebringking

Regardez cette question et répondez: Comment centrer une application WPF sur un écran?

Vous pouvez utiliser les fonctions décrites dans Windows.Forms.Screen pour obtenir l'écran en cours . Ensuite, vous pouvez peut-être définir le StartupLocation des fenêtres sur cet écran (avant de l'agrandir comme vous l'avez déjà fait). prenez le temps d'essayer moi-même, pour être honnête.

2
Simon D.

J'ai posé une question similaire qui pourrait vous être utile. Comment créer une fenêtre WPF agrandie à l'écran avec le curseur de la souris?

2
Eben Geer

Nous ne pouvons pas maximiser la fenêtre tant qu'elle n'est pas chargée. Donc, en accrochant l'événement Loaded de fullScreenWindow et en gérant l'événement le long des lignes suivantes:

private void Window_Loaded(object sender, RoutedEventArgs e) 
{
    WindowState = WindowState.Maximized;
}
1
Sibin

J'ai eu mon application obtenir maximisée dans l'écran secondaire en faisant cela

Ajoutez ceci en haut de la fenêtre principale:

using Screen = System.Windows.Forms.Screen;

Ajoutez ceci dans le gestionnaire de maximisation:

private void AdjustWindowSize()
    {
        if (this.WindowState == WindowState.Maximized)
        {
            this.WindowState = WindowState.Normal;
        }
        else
        {
            System.Drawing.Rectangle r = Screen.GetWorkingArea(new System.Drawing.Point((int)this.Left, (int)this.Top));
            this.MaxWidth = r.Width;
            this.MaxHeight = r.Height;
            this.WindowState = WindowState.Maximized;
        }
    }

Et c'est parti !

0
Christophe

l’application c # commence d’abord sur l’écran principal, à moins que votre code ne soit déplacé, votre code fonctionnera. Toutefois, si votre application wpf doit être déplacée vers un autre affichage, le nouvel emplacement peut être enregistré et stocké dans un fichier de configuration local. Mais, votre application n'aura pas de frontières ni aucun autre contrôle natif, vous devrez donc également implémenter le bit de déplacement. et lorsque votre fenêtre sera déplacée, vous pourrez capturer l'index d'affichage à l'aide de SystemParameters.

Bonne chance

0
zukas

Je viens de rencontrer le même problème. Dans mon cas, c’était le fait que je cachais ma fenêtre contextuelle lorsque j’en avais fini. Donc, si je l’appelais la prochaine fois et lui demandais d’agrandir, il le ferait sur l’écran initial. Une fois que j'ai commencé à le fermer, il a commencé à être agrandi sur le bon écran.

0
Eternal21