Как в windows forms убрать кнопку развернуть

Как убрать кнопку с верхней панели окна C# Решение и ответ на вопрос 26461

45 / 44 / 7

Регистрация: 15.10.2008

Сообщений: 320

1

Как убрать кнопку с верхней панели окна

17.03.2009, 15:29. Показов 31624. Ответов 5


Здравствуйте.
У меня такая проблемка. Необходимо убрать кнопку «развернуть на весь экран». Как это сделать.
и еще а в другом окне ее наоборот почемуто нет(только кнопка «закрыть»). Как добавить кнопки развернуть и свернуть.
Заранее спасибо.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

17.03.2009, 15:36

2

Свойство формы
MaximizeBox, MinimizeBox



6



45 / 44 / 7

Регистрация: 15.10.2008

Сообщений: 320

17.03.2009, 15:41

 [ТС]

3

IT-Skyline, подождика….. я спрашивал как добавить кнопочкив верхней панельки самого окна



0



Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

17.03.2009, 15:42

4

так выставь эти свойства в true и будет тебе счастье

Добавлено через 37 секунд
а false убрать их



1



45 / 44 / 7

Регистрация: 15.10.2008

Сообщений: 320

17.03.2009, 15:49

 [ТС]

5

кстати , если можно с кусочком кода)))

Добавлено через 1 минуту 17 секунд
хм.. он просто неактивно теперь



0



MAcK

Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

17.03.2009, 15:49

6

Вообще-то это делается в инспекторе, но уж ладно:

C#
1
2
this.MaximizeBox = true;
this.MinimizeBox = true;



4



In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don’t mind doing p/invokes to Win32 dlls.

Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized?

asked Nov 25, 2008 at 22:30

Filip Frącz's user avatar

Filip FrączFilip Frącz

5,85111 gold badges44 silver badges67 bronze badges

I read your comment in regards to my response and was able to drum up a more complete solution for you. I ran this quickly and it seemed to have the behavior that you wanted. Instead of deriving your winforms from Form, derive from this class:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {
            AllowMinimize = true;
        }

        protected override void WndProc(ref Message m)
        {
            if (!AllowMinimize)
            {
                if (m.Msg == WM_SYSCOMMAND)
                {
                    if (m.WParam.ToInt32() == SC_MINIMIZE)
                    {
                        m.Result = IntPtr.Zero;
                        return;
                    }
                }
            }
            base.WndProc(ref m);
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Specifies whether to allow the window to minimize when the minimize button and command are enabled.")]
        [DefaultValue(true)]
        public bool AllowMinimize
        {
            get;
            set;
        }
    }
}

You could do a bit more if you wanted to be able to decide whether to allow minimizing at the time the click is sent, for instance:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {

        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed())
                {
                    m.Result = IntPtr.Zero;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        private bool CheckMinimizingAllowed()
        {
            CancelEventArgs args = new CancelEventArgs(false);
            OnMinimizing(args);
            return !args.Cancel;
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Allows a listener to prevent a window from being minimized.")]
        public event CancelEventHandler Minimizing;

        protected virtual void OnMinimizing(CancelEventArgs e)
        {
            if (Minimizing != null)
                Minimizing(this, e);
        }
    }
}

For more information about this window notification, see the MSDN article about it.

answered Nov 26, 2008 at 9:28

Rob's user avatar

RobRob

3,1562 gold badges22 silver badges25 bronze badges

form.MinimizeBox = false;

or if in the form scope

MinimizeBox = false;

answered Nov 25, 2008 at 22:37

Coincoin's user avatar

CoincoinCoincoin

27.5k7 gold badges54 silver badges76 bronze badges

4

Just do MinimizeBox = false; in your form’s code.

answered Nov 25, 2008 at 22:38

Will Dean's user avatar

Will DeanWill Dean

38.9k11 gold badges89 silver badges118 bronze badges

Put this code in your form’s Resize event:

if (this.WindowState == FormWindowState.Minimized)
{
    this.WindowState = FormWindowState.Normal;
}

This will make your form un-minimizable (DISCLAIMER: I do not advocate altering the standard behavior of windows in this way).

answered Nov 25, 2008 at 22:58

MusiGenesis's user avatar

MusiGenesisMusiGenesis

73.7k40 gold badges187 silver badges332 bronze badges

You can also implement handle to the Minimize event to cancel the command

answered Nov 25, 2008 at 22:56

sebagomez's user avatar

sebagomezsebagomez

9,4217 gold badges50 silver badges89 bronze badges

0

Don’t. Don’t mess with my windows. They are mine, not yours. It is my computer and if I want to minimize, I should be able to. I can’t think of, and have never been given, a good reason for doing this.

answered Nov 25, 2008 at 23:02

Kevin's user avatar

KevinKevin

7,09611 gold badges46 silver badges70 bronze badges

3

Coincoin’s answer is correct. MinimizeBox is also available as a property in the designer properties window.

@Kevin: While I appreciate the sentiment, that’s not always a valid answer. If the application displays a modal dialog box by creating a new instance of a Form and then calling .ShowDialog() on it, you don’t want the user to minimize that Form, because then all input on the main UI thread is blocked until that Form’s modal status is satisfied. The user could potentially click on the main form and just get the «ding ding ding» unresponsive sound from Windows and not know what to do.

answered Nov 25, 2008 at 23:11

Rob's user avatar

RobRob

3,1562 gold badges22 silver badges25 bronze badges

2

just set the MinimizeBox property of your form to false.
this will disable the minimize button but other buttons will remain functional.

answered May 28, 2015 at 11:52

Apurva Shrestha's user avatar

In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don’t mind doing p/invokes to Win32 dlls.

Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized?

asked Nov 25, 2008 at 22:30

Filip Frącz's user avatar

Filip FrączFilip Frącz

5,85111 gold badges44 silver badges67 bronze badges

I read your comment in regards to my response and was able to drum up a more complete solution for you. I ran this quickly and it seemed to have the behavior that you wanted. Instead of deriving your winforms from Form, derive from this class:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {
            AllowMinimize = true;
        }

        protected override void WndProc(ref Message m)
        {
            if (!AllowMinimize)
            {
                if (m.Msg == WM_SYSCOMMAND)
                {
                    if (m.WParam.ToInt32() == SC_MINIMIZE)
                    {
                        m.Result = IntPtr.Zero;
                        return;
                    }
                }
            }
            base.WndProc(ref m);
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Specifies whether to allow the window to minimize when the minimize button and command are enabled.")]
        [DefaultValue(true)]
        public bool AllowMinimize
        {
            get;
            set;
        }
    }
}

You could do a bit more if you wanted to be able to decide whether to allow minimizing at the time the click is sent, for instance:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {

        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed())
                {
                    m.Result = IntPtr.Zero;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        private bool CheckMinimizingAllowed()
        {
            CancelEventArgs args = new CancelEventArgs(false);
            OnMinimizing(args);
            return !args.Cancel;
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Allows a listener to prevent a window from being minimized.")]
        public event CancelEventHandler Minimizing;

        protected virtual void OnMinimizing(CancelEventArgs e)
        {
            if (Minimizing != null)
                Minimizing(this, e);
        }
    }
}

For more information about this window notification, see the MSDN article about it.

answered Nov 26, 2008 at 9:28

Rob's user avatar

RobRob

3,1562 gold badges22 silver badges25 bronze badges

form.MinimizeBox = false;

or if in the form scope

MinimizeBox = false;

answered Nov 25, 2008 at 22:37

Coincoin's user avatar

CoincoinCoincoin

27.5k7 gold badges54 silver badges76 bronze badges

4

Just do MinimizeBox = false; in your form’s code.

answered Nov 25, 2008 at 22:38

Will Dean's user avatar

Will DeanWill Dean

38.9k11 gold badges89 silver badges118 bronze badges

Put this code in your form’s Resize event:

if (this.WindowState == FormWindowState.Minimized)
{
    this.WindowState = FormWindowState.Normal;
}

This will make your form un-minimizable (DISCLAIMER: I do not advocate altering the standard behavior of windows in this way).

answered Nov 25, 2008 at 22:58

MusiGenesis's user avatar

MusiGenesisMusiGenesis

73.7k40 gold badges187 silver badges332 bronze badges

You can also implement handle to the Minimize event to cancel the command

answered Nov 25, 2008 at 22:56

sebagomez's user avatar

sebagomezsebagomez

9,4217 gold badges50 silver badges89 bronze badges

0

Don’t. Don’t mess with my windows. They are mine, not yours. It is my computer and if I want to minimize, I should be able to. I can’t think of, and have never been given, a good reason for doing this.

answered Nov 25, 2008 at 23:02

Kevin's user avatar

KevinKevin

7,09611 gold badges46 silver badges70 bronze badges

3

Coincoin’s answer is correct. MinimizeBox is also available as a property in the designer properties window.

@Kevin: While I appreciate the sentiment, that’s not always a valid answer. If the application displays a modal dialog box by creating a new instance of a Form and then calling .ShowDialog() on it, you don’t want the user to minimize that Form, because then all input on the main UI thread is blocked until that Form’s modal status is satisfied. The user could potentially click on the main form and just get the «ding ding ding» unresponsive sound from Windows and not know what to do.

answered Nov 25, 2008 at 23:11

Rob's user avatar

RobRob

3,1562 gold badges22 silver badges25 bronze badges

2

just set the MinimizeBox property of your form to false.
this will disable the minimize button but other buttons will remain functional.

answered May 28, 2015 at 11:52

Apurva Shrestha's user avatar

свернуть развернуть закрыть

Как в C# убрать кнопки «свернуть», «развернуть» и «закрыть» из заголовка окна?

Если Вам вдруг вздумалось убрать по каким-то причинам кнопки «свернуть», «развернуть» и «закрыть», которые по умолчанию находятся в правом верхнем углу окна приложения, создаваемого, в частности, на языке C#, то Вам нужно подкорректировать некоторые свойства этого окна.

Убираем кнопку «закрыть»

За наличие кнопки «закрыть» отвечает свойство ControlBox. Значение false уберет данную кнопку из заголовка.

Убираем кнопки «свернуть», «развернуть»

За наличие или отсутствие кнопок «свернуть» и «развернуть» в ответе свойства MinimizeBox и MaximizeBox. Значение true добавляет, а false отбирает данные кнопки из заголовка окна Вашего приложения.

Как убрать иконку приложения из заголовка?

Если Вам не нравится иконка приложения, то Вы можете заменить его через свойство Icon. Но если же все довольно серьезно и Вы готовы порвать все отношения с данной иконкой, то Вам пригодится свойство ShowIcon. Переведите это свойства с состояние false и будем Вам счастье.

Как запретить приложению отображаться в панели задач?

За данный фокус отвечает свойство ShowInTaskbar. Если перевести данное свойство в состояние false, то Вы добьетесь желаемого результата. Таким образом Вы сможете неплохо спрятать Ваше приложение.

7 ответов

Form имеет два свойства, называемые MinimizeBox и MaximizeBox, установите оба из них в false.

Чтобы остановить закрытие формы, обработайте событие FormClosing и установите там e.Cancel = true; и после этого установите WindowState = FormWindowState.Minimized;, чтобы свести к минимуму форму.

Hans Olsson
11 июнь 2010, в 20:19

Поделиться

Привяжите обработчик к событию FormClosing, затем установите e.Cancel = true и установите форму this.WindowState = FormWindowState.Minimized.

Если вы хотите когда-либо закрыть форму, создайте класс boolean _close в классе, а в вашем обработчике установите e.Cancel на !_close, чтобы каждый раз, когда пользователь нажимает кнопку X в окне, он не закрывается, но вы все равно можете закрыть его (без его убийства) с помощью close = true; this.Close();

(И чтобы завершить мой ответ) установите MaximizeBox и MinimizeBox свойства формы в False.

dlras2
11 июнь 2010, в 22:09

Поделиться

Задайте свойства формы MaximizeBox и MinimizeBox для False

volody
11 июнь 2010, в 21:01

Поделиться

Щелкните правой кнопкой мыши форму, которую вы хотите скрыть, выберите «Элементы управления» → «Свойства».

В свойствах задайте

  • Блок управления → False
  • Свернуть окно → False
  • Максимальное поле → Ложно

Вы сделаете это в дизайнере.

Arunkumar P
24 окт. 2014, в 12:45

Поделиться

вы можете просто отключить максимизацию внутри конструктора форм.

 public Form1(){
     InitializeComponent();
     MaximizeBox = false;
 }

для минимизации при закрытии.

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    e.Cancel = true;
    WindowState = FormWindowState.Minimized;
}

Sameera R.
17 дек. 2013, в 12:09

Поделиться

Как свести форму к минимуму, когда закрытие уже было получено, но как удалить кнопки минимизации и максимизации не были.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

Brackets
27 июль 2017, в 07:06

Поделиться

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

Mauricio Kenny
28 март 2019, в 09:30

Поделиться

Ещё вопросы

  • 1Mirth Javascript импорт
  • 1Отображение значений в (Py) Spark DataFrame
  • 1Android — Какие классы использовать для разработки игр пользовательского интерфейса
  • 1Функция <T> для конкретных, а не универсальных
  • 1Неожиданное поведение JSON.stringify с массивами на конкретном веб-сайте
  • 1Сбой TcpListener.AcceptSocket () в службе Windows
  • 1Как я могу получить IP хоста в Docker-контейнере, используя Python?
  • 0htmlentities не работает на одинарные кавычки
  • 0CakePHP проверить, существуют ли методы или функции и перенаправить соответственно
  • 0Получение пустого массива $ _FILES для некоторых конкретных файлов изображений
  • 0Уведомления COM-интерфейса VDS (Virtual Disk Service) — обратный вызов (приемник), вызываемый только во время отмены регистрации (Unadvise)
  • 0Невозможно отобразить полученное значение из базы данных в codeIgniter
  • 1Невозможно получить доступ к функции внутри функции JavaScript
  • 1Запуск Google Maps с большим количеством параметров
  • 0Сохранение данных дает ошибку, параметр отсутствует или значение пусто
  • 0Неправильное поведение с кодом AngularJS
  • 1Исключение в потоке «основной» java.lang.ArrayIndexOutOfBoundsException в java.lang.System.arraycopy (собственный метод)
  • 1Как выровнять по горизонтали некоторые программно добавленные виды?
  • 1Несколько звонков на веб-сервисы из Node.js
  • 0Сделайте функцию, чтобы видеть только определенную часть DOM
  • 0Почему onmouseover и onclick не будут работать вместе, устанавливая стили div, и как сбросить стили набора onclick, не теряя onmouseover?
  • 0Неудачный флаг проверки в jquery
  • 0От шестнадцатеричного к декабрьскому до пользовательского RGB = не печатает цифру «0 (ноль)»
  • 1Почему я не могу наследовать от частного класса / интерфейса?
  • 1Нахождение термина в списке
  • 1Вызов функции внутри If..If Else..Else внутри скрипта google-app
  • 0Как получить атрибут раскрывающегося списка в jquery
  • 0INNER JOIN table1.id = table2.id и col1 = null и col2 = not null
  • 1Как получить результат / обратная связь / количество строк / количество строк, затронутых запросом MERGE во фрагменте Python
  • 1Загрузка файла с использованием RESTful API на основе плагина Grails JAX-RS
  • 0Как получить доступ к ассоциативному массиву в yii2
  • 0Mysql Выбор группы по и без группировки в одном запросе
  • 1Запуск другого действия создает пустой экран и вылетает
  • 1Есть ли способ расширить уведомления нажатием клавиши, а не касанием?
  • 1Захват части группы
  • 1Перетаскивание в список
  • 0Как узнать, доступен ли уровень отладки dx?
  • 1Почему событие отметки времени в новом классе вызывает метод из form1 один раз, а в следующий раз он ничего не делает?
  • 1Ошибка построения панд TypeError: Пусто ‘DataFrame’: нет числовых данных для построения графика
  • 0Триггерное событие ввода в угловых
  • 0Как получить все соответствующие записи respectievelijk из базы данных MySql, используя php, который хранится в массиве?
  • 1Написание объектов из потока в Android
  • 1можно добавить ChartRangeFilter в пузырьковую диаграмму?
  • 0Нужны эти два <div> рядом
  • 0Как сделать несколько запросов в Spring Batch (в частности, используйте LAST_INSERT_ID ())
  • 1Entity Framework — Компонент внешнего ключа… не является объявленным свойством типа
  • 0Raw Socket отправляет TCP SYN-FIN- .. в C ++
  • 0CSS3 Преобразование FireFox / Chrome против 11
  • 0Knockout не является обязательным для отправки с JQuery1.10.2
  • 0MYSQL LEFT JOIN 3 таблицы (1-я таблица возвращает пустые значения)
  • Remove From My Forums

 none

Как убрать кнопки с формы

  • Вопрос

  • Кто знает, как убрать в программе 3 стандартные кнопки закрыть, свернуть и развернуть? не меняя WindowStyle,

    И как сделать чтоб нельзя было изменять размер формы, не меняя ResizeMode

    WPF

Ответы

  • Здравствуйте.

    Это можно сделать задав необходимые стили для окна с помощью WinAPI функции

    SetWindowLongPtr

    Ниже приведен класс-хелпер, который позволяет установить необходимые стили, а также предоставляет зависимые свойства, чтобы стили окна можно было указывать в xaml разметке. Вы можете использовать его, или взять только задание стиля, объединить нужные стили
    и задать их в событии Loaded окна. (Источники класса —
    WPF Window – Disable Minimize and Maximize Buttons Through Attached Properties From XAM,

    How to hide close button in wpf window?,
    Disable Window Resizing Win32)

    Использование:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:WindowCustomizerExample"
        Title="MainWindow" Height="350" Width="525"
        local:WindowCustomizer.CanMaximize="False"
        local:WindowCustomizer.CanMinimize="False"
        local:WindowCustomizer.CanClose="False"
        local:WindowCustomizer.Sizeble="False">
      <Grid>
        
      </Grid>
    </Window>
    
    

    Сам класс:

    using System;
    using System.Runtime.InteropServices;
    using System.Windows;
    using System.Windows.Interop;
    
    namespace WindowCustomizerExample
    {
      public static class WindowCustomizer
      {
        #region Sizeble
        public static readonly DependencyProperty Sizeble =
          DependencyProperty.RegisterAttached("Sizeble", typeof(bool), typeof(Window),
            new PropertyMetadata(true, new PropertyChangedCallback(OnSizebleChanged)));
        private static void OnSizebleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
          Window window = d as Window;
          if (window != null)
          {
            RoutedEventHandler loadedHandler = null;
            loadedHandler = delegate
            {
              if ((bool)e.NewValue)
              {
                WindowHelper.EnableSizeBox(window);
              }
              else
              {
                WindowHelper.DisableSizeBox(window);
              }
              window.Loaded -= loadedHandler;
            };
    
            if (!window.IsLoaded)
            {
              window.Loaded += loadedHandler;
            }
            else
            {
              loadedHandler(null, null);
            }
          }
        }
        public static void SetSizeble(DependencyObject d, bool value)
        {
          d.SetValue(Sizeble, value);
        }
        public static bool GetSizeble(DependencyObject d)
        {
          return (bool)d.GetValue(Sizeble);
        }
        #endregion
    
        #region CanClose
        public static readonly DependencyProperty CanClose =
          DependencyProperty.RegisterAttached("CanClose", typeof (bool), typeof (Window),
            new PropertyMetadata(true, new PropertyChangedCallback(OnCanCloseChanged)));
        private static void OnCanCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
          Window window = d as Window;
          if (window != null)
          {
            RoutedEventHandler loadedHandler = null;
            loadedHandler = delegate
            {
              if ((bool) e.NewValue)
              {
                WindowHelper.EnableClose(window);
              }
              else
              {
                WindowHelper.DisableClose(window);
              }
              window.Loaded -= loadedHandler;
            };
    
            if (!window.IsLoaded)
            {
              window.Loaded += loadedHandler;
            }
            else
            {
              loadedHandler(null, null);
            }
          }
        }
        public static void SetCanClose(DependencyObject d, bool value)
        {
          d.SetValue(CanClose, value);
        }
        public static bool GetCanClose(DependencyObject d)
        {
          return (bool) d.GetValue(CanClose);
        }
        #endregion
    
        #region CanMaximize
        public static readonly DependencyProperty CanMaximize =
          DependencyProperty.RegisterAttached("CanMaximize", typeof(bool), typeof(Window),
            new PropertyMetadata(true, new PropertyChangedCallback(OnCanMaximizeChanged)));
        private static void OnCanMaximizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
          Window window = d as Window;
          if (window != null)
          {
            RoutedEventHandler loadedHandler = null;
            loadedHandler = delegate
            {
              if ((bool)e.NewValue)
              {
                WindowHelper.EnableMaximize(window);
              }
              else
              {
                WindowHelper.DisableMaximize(window);
              }
              window.Loaded -= loadedHandler;
            };
    
            if (!window.IsLoaded)
            {
              window.Loaded += loadedHandler;
            }
            else
            {
              loadedHandler(null, null);
            }
          }
        }
        public static void SetCanMaximize(DependencyObject d, bool value)
        {
          d.SetValue(CanMaximize, value);
        }
        public static bool GetCanMaximize(DependencyObject d)
        {
          return (bool)d.GetValue(CanMaximize);
        }
        #endregion CanMaximize
    
        #region CanMinimize
        public static readonly DependencyProperty CanMinimize =
          DependencyProperty.RegisterAttached("CanMinimize", typeof(bool), typeof(Window),
            new PropertyMetadata(true, new PropertyChangedCallback(OnCanMinimizeChanged)));
        private static void OnCanMinimizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
          Window window = d as Window;
          if (window != null)
          {
            RoutedEventHandler loadedHandler = null;
            loadedHandler = delegate
            {
              if ((bool)e.NewValue)
              {
                WindowHelper.EnableMinimize(window);
              }
              else
              {
                WindowHelper.DisableMinimize(window);
              }
              window.Loaded -= loadedHandler;
            };
    
            if (!window.IsLoaded)
            {
              window.Loaded += loadedHandler;
            }
            else
            {
              loadedHandler(null, null);
            }
          }
        }
        public static void SetCanMinimize(DependencyObject d, bool value)
    
        {
          d.SetValue(CanMinimize, value);
        }
        public static bool GetCanMinimize(DependencyObject d)
        {
          return (bool)d.GetValue(CanMinimize);
        }
        #endregion CanMinimize
    
        #region WindowHelper Nested Class
    
        public static class WindowHelper
        {
          private const Int32 GWL_STYLE = -16;
          private const Int32 WS_SYSMENU = 0x80000;
          private const Int32 WS_MAXIMIZEBOX = 0x00010000;
          private const Int32 WS_MINIMIZEBOX = 0x00020000;
          private const Int32 WS_SIZEBOX = 0x40000;
    
          [DllImport("User32.dll", EntryPoint = "GetWindowLong")]
          private static extern Int32 GetWindowLongPtr(IntPtr hWnd, Int32 nIndex);
    
          [DllImport("User32.dll", EntryPoint = "SetWindowLong")]
          private static extern Int32 SetWindowLongPtr(IntPtr hWnd, Int32 nIndex, Int32 dwNewLong);
    
          /// <summary>
          /// Disables the close functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void DisableClose(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_SYSMENU);
            }
          }
    
          /// <summary>
          /// Disables the maximize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void DisableMaximize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_MAXIMIZEBOX);
            }
          }
    
          /// <summary>
          /// Disables the minimize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void DisableMinimize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_MINIMIZEBOX);
            }
          }
    
          /// <summary>
          /// Disables the resize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void DisableSizeBox(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_SIZEBOX);
            }
          }
    
          /// <summary>
          /// Enables the close functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void EnableClose(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_SYSMENU);
            }
          }
    
          /// <summary>
          /// Enables the maximize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void EnableMaximize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_MAXIMIZEBOX);
            }
          }
    
          /// <summary>
          /// Enables the minimize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void EnableMinimize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_MINIMIZEBOX);
            }
          }
    
          /// <summary>
          /// Enables the resize functionality of a WPF window.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void EnableSizeBox(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
              SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_SIZEBOX);
            }
          }
    
    
          /// <summary>
          /// Toggles the enabled state of a WPF window's close functionality.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void ToggleClose(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
    
              if ((windowStyle | WS_SYSMENU) == windowStyle)
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_SYSMENU);
              }
              else
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_SYSMENU);
              }
            }
          }
    
          /// <summary>
          /// Toggles the enabled state of a WPF window's maximize functionality.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void ToggleMaximize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
    
              if ((windowStyle | WS_MAXIMIZEBOX) == windowStyle)
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_MAXIMIZEBOX);
              }
              else
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_MAXIMIZEBOX);
              }
            }
          }
    
          /// <summary>
          /// Toggles the enabled state of a WPF window's minimize functionality.
          /// </summary>
          /// <param name="window">The WPF window to be modified.</param>
          public static void ToggleMinimize(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
    
              if ((windowStyle | WS_MINIMIZEBOX) == windowStyle)
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_MINIMIZEBOX);
              }
              else
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_MINIMIZEBOX);
              }
            }
          }
    
          public static void ToggleSizeBox(Window window)
          {
            lock (window)
            {
              IntPtr hWnd = new WindowInteropHelper(window).Handle;
              Int32 windowStyle = GetWindowLongPtr(hWnd, GWL_STYLE);
    
              if ((windowStyle | WS_SIZEBOX) == windowStyle)
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle & ~WS_SIZEBOX);
              }
              else
              {
                SetWindowLongPtr(hWnd, GWL_STYLE, windowStyle | WS_SIZEBOX);
              }
            }
          }
        }
        #endregion WindowHelper Nested Class
      }
    }
    
    

    Для связи [mail]

    • Помечено в качестве ответа

      20 июля 2011 г. 11:38

Я прочитал ваш комментарий относительно моего ответа и смог предложить вам более полное решение. Я побежал так быстро, и, похоже, он вел себя так, как вы хотели. Вместо того, чтобы унаследовать ваши winforms от Form, унаследуйте от этого класса:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {
            AllowMinimize = true;
        }

        protected override void WndProc(ref Message m)
        {
            if (!AllowMinimize)
            {
                if (m.Msg == WM_SYSCOMMAND)
                {
                    if (m.WParam.ToInt32() == SC_MINIMIZE)
                    {
                        m.Result = IntPtr.Zero;
                        return;
                    }
                }
            }
            base.WndProc(ref m);
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Specifies whether to allow the window to minimize when the minimize button and command are enabled.")]
        [DefaultValue(true)]
        public bool AllowMinimize
        {
            get;
            set;
        }
    }
}

Вы могли бы сделать немного больше, если бы хотели иметь возможность решать, разрешать ли минимизацию во время отправки щелчка, например:


using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace NoMinimizeTest
{
    public class MinimizeControlForm : Form
    {
        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xf020;

        protected MinimizeControlForm()
        {

        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed())
                {
                    m.Result = IntPtr.Zero;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        private bool CheckMinimizingAllowed()
        {
            CancelEventArgs args = new CancelEventArgs(false);
            OnMinimizing(args);
            return !args.Cancel;
        }

        [Browsable(true)]
        [Category("Behavior")]
        [Description("Allows a listener to prevent a window from being minimized.")]
        public event CancelEventHandler Minimizing;

        protected virtual void OnMinimizing(CancelEventArgs e)
        {
            if (Minimizing != null)
                Minimizing(this, e);
        }
    }
}

Для получения дополнительной информации об этом уведомлении об этом окне см. Статья MSDN об этом.

Понравилась статья? Поделить с друзьями:
  • Как в виртуал бокс запустить windows
  • Как в биосе поставить загрузку с флешки на windows 10 asus
  • Как в windows forms поставить картинку на фон
  • Как в виндовс xp отключить пароль при входе в windows
  • Как в биосе поставить загрузку с флешки на windows 10 acer