Wpf disable windows close button

How to Enable/Disable button in wpf

I Have 2 button , Start And capture. I want disable capture button on form load and enable start. and on after click on start disable start button and enable capture. Please help me. Thanks in advance

5 Answers 5


you can disable Capture by xaml and then enable it by writing code in c#.

for enable and disable use IsEnabled Property. and for clicking on the button use Click event.

Set IsEnabled=»False» to disable the button

Set IsEnabled=»True» to enable the button

Hope this helps

You should store current state in some variable (e.g. _capturing ). When variable changing, you refresh IsEnabled property.

UPDATE

You should add click handler and your xaml code will work:

Yes I got my answer. Just make simeple solution

There are two ways to disable a button In C# WPF.

  1. In .xaml File
    Using IsEnabled=»False» . If you set False to IsEnabled attribute, then your button will be disabled by default.
  2. In .cs File
    ButtonName.IsEnabled = false; If you set IsEnabled property as false for the button, it will disable the button

Not the answer you’re looking for? Browse other questions tagged wpf or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Wpf disable windows close button

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

How do you disable Minimize, Maximize, Close buttons + remove app icon on a WPF window? Any help doing this would be appreciated.

Answers

Set the Window.WindowStyle property to WindowStyle.None.

All replies

Set the Window.WindowStyle property to WindowStyle.None.

I just tried this — it does a bit too much, removing the whole window title and border. I am trying to mimick a normal modal dialog with no icon in the title bar, and no minimize/maximize, possibly no close button.

I just tried setting the WindowStyle to SingleBorderWindow — this is almost what I want: I would like the possibilty of showing/hiding the Window Icon in the titlebar and the close button.

Seems this was overlooked in WPF. Shouldn’t there be an equivilent of the MinimizeBox and MaximizeBox properties that are present in Windows Forms.

Any ideas on a workaround to disable the minimize button and leave the maximize and close button on the window?

Can someone comment on this from MSFT? What is the bext practise for disabling the Minimize / Maximize buttons when using a WPF window? I look forward to a response fro MSFT

Disabling Minimize, Maximize buttons:

This can be achieved by setting Window.ResizeMode property to ResizeMode.NoResize. It will disable the minimize and maximize buttons. Furthermore, the window will not resize by mouse click+drag.

Not showing Icon and Close button:

Unfortunately, this feature is not available in WPF. To achieve this, you can try setting the WS_EX_DLGMODALFRAME window style by calling [Get/Set]WindowLong (pInvoking in to Win32) from the SourceInitialized event on the Window class.

Private Shared Function SetWindowLong( ByVal hWnd As IntPtr, ByVal nIndex As Integer , ByVal dwNewLong As Integer ) As Integer

Private Shared Function GetWindowLong( ByVal hWnd As IntPtr, ByVal nIndex As Integer ) As Integer

Private Const GWL_STYLE As Integer = (-16)

Читайте также:  Что может киностудия windows live

Private Sub RemoveControlBoxes()

Dim hwnd As IntPtr = New Interop.WindowInteropHelper( Me ).Handle

Dim windowLong As Long = GetWindowLong(hwnd, GWL_STYLE)

windowLong = windowLong And -131073 And -65537

SetWindowLong(hwnd, GWL_STYLE, CInt (windowLong))

The above VB.NET code should remove the Minimize and Max. control buttons within the Window frame. Also, pinvoke.net is a handy resource for future reference.

Hamid says «To Disable Maximize and Minimize, set Window.ResizeMode property to ResizeMode.NoResize.»

Ok, I don’t want to stop all resizing.
What I want to do is allow resizing (between the min and max dimensions) but no maximising or minimising. How do I go about that?

Certainly the Minimize button should be disabled when the window is not resizable, but I should still be able to turn off the button and keep my window resizable.

Second, the minimize on a modal dialog owned by main window behaves very poorly. The dialog minimizes, focus changes to another application, say Live Messenger, but the main window of the application remains in the background and is disabled. Now if the Messenger isn’t maximized, the disabled main window shows behind it and looks for all purposes like it ready to go — except its disabled.

This will trip up my users. I need to be able to turn the button off with out resorting to resize functionality on the dialog.

How to hide close button in WPF window?

I’m writing a modal dialog in WPF. How do I set a WPF window to not have a close button? I’d still like for its WindowState to have a normal title bar.

I found ResizeMode , WindowState , and WindowStyle , but none of those properties allow me to hide the close button but show the title bar, as in modal dialogs.

21 Answers 21

WPF doesn’t have a built-in property to hide the title bar’s Close button, but you can do it with a few lines of P/Invoke.

First, add these declarations to your Window class:

Then put this code in the Window’s Loaded event:

And there you go: no more Close button. You also won’t have a window icon on the left side of the title bar, which means no system menu, even when you right-click the title bar — they all go together.

Important note: all this does is hide the button. The user can still close the window! If the user presses Alt + F4 , or closes the app via the taskbar, the window will still close.

If you don’t want to allow the window to close before the background thread is done, then you could also override OnClosing and set Cancel to true, as Gabe suggested.

I just got to similar problem and Joe White’s solution seems to me simple and clean. I reused it and defined it as an attached property of Window

Then in XAML you just set it like this:

Set WindowStyle property to None which will hide the control box along with the title bar. No need to kernal calls.

This won’t get rid of the close button, but it will stop someone closing the window.

Put this in your code behind file:

To disable close button you should add the following code to your Window class (the code was taken from here, edited and reformatted a bit):

This code also disables close item in System menu and disallows closing the dialog using Alt+F4.

You will probably want to close the window programmatically. Just calling Close() will not work. Do something like this:

I was trying Viachaslau’s answer since I like the idea of not removing the button but disabling it, but for some reason it did not always work: the close button was still enabled but no errors whatsoever.

This on the other hand always worked (error checking omitted):

The property to set is => WindowStyle=»None»

I just add my implementation of Joe White’s answer using Interactivity Behavior (you need to reference System.Windows.Interactivity).

Читайте также:  Как изменить системное время linux

Let the user «close» the window but really just hide it.

In the window’s OnClosing event, hide the window if already visible:

Each time the Background thread is to be executed, re-show background UI window:

When terminating execution of program, make sure all windows are/can-be closed:

So, pretty much here is your problem. The close button on the upper right of a window frame is not part of the WPF window, but it belongs to the part of the window frame that is controled by your OS. This means you will have to use Win32 interop to do it.

alternativly, you can use the noframe and either provide your own «frame» or have no frame at all.

The following is about disabling the close and Maximize/Minimize buttons, it does not actually remove the buttons (but it does remove the menu items!). The buttons on the title bar are drawn in a disabled/grayed state. (I’m not quite ready to take over all the functionality myself ^^)

This is slightly different than Virgoss solution in that it removes the menu items (and the trailing separator, if needed) instead of just disabling them. It differs from Joe Whites solution as it does not disable the entire system menu and so, in my case, I can keep around the Minimize button and icon.

The follow code also supports disabling the Maximize/Minimize buttons as, unlike the Close button, removing the entries from the menu does not cause the system to render the buttons «disabled» even though removing the menu entries does disable the functionality of the buttons.

It works for me. YMMV.

Usage: This must be done AFTER the source is initialized. A good place is to use the SourceInitialized event of the Window:

To disable the Alt+F4 functionality the easy method is just to wire up the Canceling event and use set a flag for when you really do want to close the window.

Как скрыть кнопку закрытия в окне WPF?

Я пишу модальный диалог в WPF. Как настроить окно WPF, чтобы у него не было кнопки закрытия? Я бы все равно хотел, чтобы его WindowState имел обычную строку заголовка.

Я нашел ResizeMode, WindowState и WindowStyle, но ни одно из этих свойств не позволяет мне скрыть кнопку закрытия, но показать строку заголовка, как в модальных диалогах.

19 ответов:

WPF не имеет встроенного свойства, чтобы скрыть кнопку закрытия строки заголовка, но вы можете сделать это с помощью нескольких строк P/Invoke.

во-первых, добавьте эти объявления в свой класс окна:

затем поместите этот код в загруженное событие окна:

и там вы идете: нет больше кнопки «Закрыть». У вас также не будет значка окна в левой части строки заголовка, что означает отсутствие системного меню, даже если вы щелкните правой кнопкой мыши строку заголовка — все они идут вместе.

обратите внимание, что Alt+F4 все равно закроет окно. Если вы не хотите, чтобы окно закрывалось до завершения фонового потока, вы также можете переопределить OnClosing и установить Cancel в true, как предложил Гейб.

Я просто добрался до подобной проблемы, и решение Джо Уайта кажется мне простым и чистым. Я повторно использовал его и определил его как вложенное свойство Window

затем в XAML вы просто установите его следующим образом:

Set WindowStyle свойство None, которое скроет поле управления вместе со строкой заголовка. Не нужно керналь звонки.

это не избавится от кнопки закрытия, но это остановит кого-то закрывать окно.

поместите это в свой код позади файла:

чтобы отключить кнопку закрытия, вы должны добавить следующий код в свой класс окна (код был взят из здесь, отредактировано и переформатировано немного):

этот код также отключает пункт Закрыть в системном меню и запрещает закрытие диалогового окна с помощью Alt+F4.

вы, вероятно, захотите закрыть окно программно. Просто звоню Close() не будет работать. Сделать что-то вроде этого:

Читайте также:  Configuring java on windows

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

это с другой стороны всегда работало (проверка ошибок опущена):

Я просто добавляю свою реализацию ответ Джо Уайта используя поведение интерактивности (вам нужно ссылаться на систему.Окна.Интерактивность.)

свойство для установки=> WindowStyle=»None»

пользователь «закрыть» окно, но на самом деле просто скрывают это.

в окне OnClosing событие, скрыть окно, если оно уже видно:

каждый раз, когда фоновый поток должен быть выполнен, повторно показать фоновое окно пользовательского интерфейса:

при завершении выполнения программы, убедитесь, что все окна могут быть закрыты:

Итак, в значительной степени здесь ваша проблема. Кнопку Закрыть в правом верхнем углу оконной рамы не является частью окна WPF, но она принадлежит часть оконной рамы, которая управляется вашей ОС. Это означает, что вам придется использовать Win32 interop для этого.

альтернативно, вы можете использовать noframe и либо предоставить свой собственный «кадр», либо вообще не иметь кадра.

следующее касается отключения кнопок закрытия и максимизации/минимизации, это делает не на самом деле удалить кнопки (но он удаляет пункты меню!). Кнопки в строке заголовка отображаются в отключенном / сером состоянии. (Я не совсем готов взять на себя всю функциональность сам^^)

это немного отличается от решения Virgoss в том, что он удаляет пункты меню (и конечный разделитель, если это необходимо) вместо того, чтобы просто отключить их. Он отличается от решения Joe Whites, поскольку оно не отключает все системное меню, и поэтому в моем случае я могу держать вокруг кнопки «свернуть» и значка.

следующий код также поддерживает отключение кнопок развернуть / свернуть, поскольку, в отличие от кнопки Закрыть, удаление записей из меню не приводит к тому, что система отображает кнопки «отключено», даже если удаление записей меню тут отключить функции кнопок.

это работает для меня. МММ.

использование: это должно быть сделано после инициализации источника. Хорошее место, чтобы использовать SourceInitialized событие окна:

чтобы отключить функциональность Alt+F4 простой способ — это просто подключить событие отмены и использовать установить флаг, когда вы действительно хотите закрыть окно.

Edit— на этот Thread показывает, как это можно сделать, но я не думаю, что окно имеет свойство, чтобы получить то, что вы хотите, не теряя нормального заголовка.

Изменить 2 Это Thread показывает способ его выполнения, но вы должны применить свой собственный стиль к системному меню, и он показывает способ, как вы можете это сделать.

Гото окне «Свойства» установите для параметра

u не получится закрыть кнопки.

попробуйте добавить в окно событие закрытия. Добавьте этот код в обработчик событий.

это предотвратит закрытие окна. Это имеет тот же эффект, что и скрытие кнопки закрытия.

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

установка WS_VISIBLE (0x10000000) и WS_OVERLAPPED (0x0) значения для стиля окна. «Перекрывается» — это необходимое значение для отображения строки заголовка и границы окна. Путем удаления WS_MINIMIZEBOX (0x20000) , WS_MAXIMIZEBOX (0x10000) и WS_SYSMENU (0x80000) значения из моего значения стиля, все кнопки из строки заголовка были удалены, включая кнопку Закрыть.

как указано в других ответах, вы можете использовать WindowStyle=»None» чтобы полностью удалить строку заголовка.

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

однако вы можете преодолеть это, добавив одну строку кода в конструктор в коде окна позади файла:

или, если вы предпочитаете лямбда-синтаксис:

Это делает все окно перетаскивается. Любые интерактивные элементы управления, присутствующие в окне, такие как кнопки, по-прежнему будут работать как обычно и не будут действовать как перетаскиваемые маркеры для окна.

использовать WindowStyle=»SingleBorderWindow» , это скроет кнопку max и min из окна WPF.

Если нужно только запретить пользователю закрывать окно, это простое решение.

код XAML: IsCloseButtonEnabled=»False»

Оцените статью