473,722 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

i want to prevent windows to close my form when Alt+f4 is pressed

Hi,
Can anybody help me, i want to prevent windows to close my winform of
..NET application, when user presses Alt+F4

Nov 17 '05 #1
7 7894
You could Handle the Closing event th following way:

private void Form1_Closing(o bject sender,
System.Componen tModel.CancelEv entArgs e)
{
e.Cancel=true;
}

"Nikki" wrote:
Hi,
Can anybody help me, i want to prevent windows to close my winform of
..NET application, when user presses Alt+F4

Nov 17 '05 #2
....Great that prevents the close (I might add *always* too!) but hardly
helps Nikki with the solution, of which the crux of it is detecting the key
events in the first place.

***Nikki*** There are possibly more elegant ways to do this (I can think of
at least one other) but they will all essentially use the following
detection. Your form will have one private var that indicates whether the
form should be allowed to close or not. You detect the press and set this
var to disallow. Then in the forms (because it will still fire) closing
event you should read this var, and allow close or not. Obviously if close
is not allowed and doesnt happen then the var should then be reset to allow
close for any future events.

The code snippet is as follows (if you want me to include the class file
then let me know). Might I also suggest that rather than preventing the
close you should handle the close i.e. provide a prompt to the user and if
they say OK then cleanup. The reason I say this is because ALT+F4 is (as you
know) known and expected behaviour -and you are taking that away (IMHO I
would say that is poor design). Personally it would annoy the hell out of
me.

private bool enableClose = true;

private void Form1_KeyDown(o bject sender,
System.Windows. Forms.KeyEventA rgs e)
{
if (e.KeyCode == Keys.F4 && e.Alt)
{
MessageBox.Show ("Sorry you cannot close this form via ALT+F4");
enableClose = false;
}
}

private void Form1_Closing(o bject sender,
System.Componen tModel.CancelEv entArgs e)
{
if (enableClose == false)
{
enableClose = true;
e.Cancel = true;
}
}

br,

Mark.
"Marinus Holkema" <Ma************ @discussions.mi crosoft.com> wrote in
message news:74******** *************** ***********@mic rosoft.com...
You could Handle the Closing event th following way:

private void Form1_Closing(o bject sender,
System.Componen tModel.CancelEv entArgs e)
{
e.Cancel=true;
}

"Nikki" wrote:
Hi,
Can anybody help me, i want to prevent windows to close my winform of
..NET application, when user presses Alt+F4

Nov 17 '05 #3


Thank you Mark. It's a gr8 help, U saved lot of my time & effort.
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #4
Absolutely no problem at all :-)
In fact you might be able to help me, if you know of any C# jobs in my
vacinity (Cambs UK) then let me know....I'm on the hunt!

"Nikki V" <ap*********@gm ail.com> wrote in message
news:e8******** ******@TK2MSFTN GP12.phx.gbl...


Thank you Mark. It's a gr8 help, U saved lot of my time & effort.
*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #5
The problem with this solution is that it prevents windows closing the program when it shuts down as well, and thereby prevents shutting down the computer.

You can detect what triggered the Closing event by parsing the 7th last StackFrame

protected override void OnClosing(Cance lEventArgs e)
{
// frames 1-6 will be identical
StackTrace st = new StackTrace(7);
StackFrame sf = st.GetFrame(0); // 7th frame

switch(sf.GetMe thod().Name)
{
case "DefWndProc ":
// user pressed Alt-F4 or clicked the X button
break;
case "SendMessag e":
// something in the code called Close()
break;
}
}

Another problem with this is that Windows itself uses DefWndProc for closing programs at ShutDown as well. You need to set a flag in DefWndProc that you can use inside the Closing event.

The procedure for this is as follows:

private bool shutdown = false;
protected override void DefWndProc(ref Message m)
{
const int WM_QUERYENDSESS ION = 0x0011;
if(m.Msg == WM_QUERYENDSESS ION)
shutdown = true;
base.DefWndProc (ref m);
}

Inside the Closing event, if shutdown is true, don't cancel the closing event.

In theory this should work, but in my test cases Windows never sent the WM_QUERYENDSESS ION message. It may work for you though.
--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #6
Mark Broadbent wrote:
private void Form1_KeyDown(o bject sender,
System.Windows. Forms.KeyEventA rgs e)
{
if (e.KeyCode == Keys.F4 && e.Alt)
{
MessageBox.Show ("Sorry you cannot close this form via ALT+F4");
enableClose = false;
}
}


Don't you have to set KeyPreview = true on the form for this to work?
Otherwise the KeyDown event gets fired in the "control-with-focus" and the
form doesn't see it but gets closed anyway.

Another idea would be to set e.Handled = true in the KeyDown event when you
detect ALT-F4. This way the key simply gets ignored and you don't need to
check enableClose in the Closing method.

Just my 2c.. I needed the same just a few days ago.

Max

Nov 17 '05 #7
Your post is of course completely correct, well spotted! Wrote my code in a
few seconds so missed those two things ;-)

"Markus Stoeger" <sp******@gmx.a t> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
Mark Broadbent wrote:
private void Form1_KeyDown(o bject sender,
System.Windows. Forms.KeyEventA rgs e)
{
if (e.KeyCode == Keys.F4 && e.Alt)
{
MessageBox.Show ("Sorry you cannot close this form via ALT+F4");
enableClose = false;
}
}


Don't you have to set KeyPreview = true on the form for this to work?
Otherwise the KeyDown event gets fired in the "control-with-focus" and the
form doesn't see it but gets closed anyway.

Another idea would be to set e.Handled = true in the KeyDown event when
you
detect ALT-F4. This way the key simply gets ignored and you don't need to
check enableClose in the Closing method.

Just my 2c.. I needed the same just a few days ago.

Max

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7162
by: waisty vb.net rookie | last post by:
How do I make sure my program cannot be closed by using Alt + F4 -- Thanks for reading
0
3809
by: Ron James | last post by:
I have a Dialog type form that starts a worker thread, allows the thread to update its progess and provides a Cancel button. Following advice from Chad Meyers in a recent posting, the worker thread updates the dialog by calling Invoke which runs the UI update method on the UI thread. This works nicely. (Thanks Chad) However, if I close the dialog using the form close button ( top right hand corner) I get an ObjectDisposedException...
3
44017
by: Stefan | last post by:
Hy, i have an app and i must disable this combination: ALT+F4; CTRL+ALT+DEL; CTRL+ESC;ALT+TAB like this: i find something on Internet and i can block ALT+F4 protected override System.Boolean ProcessCmdKey(ref System.Windows.Forms.Message msg,System.Windows.Forms.Keys keyData)
3
6441
by: 007 | last post by:
I have a FixedToolWindow form that I create and display when the user presses a button on the toolbar. I want to prevent Alt+F4 on the FixedToolWindow form. How do I accomplish this? I want the only way to close the FixedToolWindow form is by clicking on the toolbar button again. It's a bit like pressing "Search" on IE's toolbar. BTW why is the ToolBar that comes with VS.NET so ugly? It's like the old style toolbar.
2
29408
by: cashdeskmac | last post by:
I have written a small program and I want the user to close it down solely by clicking on a button. How can I disable the ALT+F4 method of closing the application down?
7
2627
by: Michael Maes | last post by:
Hello, ALT+F4 is the shortcut to close a form. When I use this shortcut in an MDI enviroment, the application is closed, so obviously the shortcut applies to the 'Container' and not to the 'Childform'. What would be the best practice to capture this event and close the active child instead of the container (thus trying to end the application). --
2
3567
by: RTT | last post by:
<form id="Form1" method="post" runat="server"> <asp:textbox id="TxtEmail" tabIndex="1" runat="server" Width="272px" ToolTip="Enter your emailaddress for authentication"></asp:textbox> <asp:textbox id="TxtPassword" tabIndex="2" runat="server" Width="272px" ToolTip="Enter your domain password" TextMode="Password"></asp:textbox> <asp:linkbutton id="BtnLogin" tabIndex="3" runat="server">Login</asp:linkbutton> </form> This is the form as i...
5
10475
by: freelancex | last post by:
Hi, Im new to this forum, and new to scripting in general. Im an ICT Technician for a high school and i am designing a Form in visual basic 2005. The intended purpose of the Form, is to prevent student users logging on to their area, without accepting the Acceptable Use Policy which comes up on screen. The form, runs maximized, in full screen mode and is constantly in focus, above all other programs. So Basically, until the form is...
9
8442
by: raknin | last post by:
Hi, I want to detect when the user close a window through the X button or ALT-F4 or when the user go to another page and leave my page. I try to use the onuload and on unloadbeore but it works on ie 6 and Firefox 2 and it doesn't work on Safari 3.03 and Opera 9.2, it is also doesn't solve the problem when the user navigate to another page through the same windows, Any Ideas? Thanks ...
0
8740
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9386
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8059
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4503
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3208
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2606
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2148
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.