简体   繁体   中英

How to prevent a disabled Form from being dragged?

The following code works as expected except that if the Form is "dragged" while disabled – when notepad exits – the Form will be in the new position. How can that be prevented?

Enabled = false;
Process p = Process.Start("notepad");
p.WaitForExit();
Enabled = true;

Okay, I repro the problem. The issue is that you are calling WaitForExit() on the UI thread. That stops it from pumping the message loop and processing input events. They will get put in the message queue. As soon as the process exits, your method returns and the UI thread starts pumping messages again. And finds the mouse messages that were buffered, executing them because the window is no longer disabled.

The general rule for code that runs on the UI thread is that it should never block. Lots of things will go wrong, this is just one example. It is easy to do with the Process class, it has an event that fires when the process exited. So you don't need to use WaitForExit(). Make your code look like this:

        this.Enabled = false;
        var prc = System.Diagnostics.Process.Start("notepad.exe");
        prc.EnableRaisingEvents = true;
        prc.SynchronizingObject = this;
        prc.Exited += delegate { 
            this.Enabled = true;
            this.Activate();
        };

Note that the Activate() call is necessary to put your window back into the foreground. This might not always work.

You could try running Process start from a second Form called with a showDialog.

Form2 frm2 =new Form2();

frm2.ShowDialog();

in the Form2 Load event put your

Process p = Process.Start("notepad");
p.WaitForExit();
this.DialogResult=DialogResult.OK;

Have to check syntax on all that it is likely not perfect.

You could even set Form2.Visible to false, so the user never even sees it.

EDIT as HomeToast suggested, This works very well, as long as you don't mind Hiding your Form, If you want to keep your Form visible I would go with my first suggestion

In this Option, we are going to Visible=false the main form, instead if Enable=false If there is no Form to Drag, the user cannot drag it.

this.Visible = false;
Process p = Process.Start("notepad");
p.WaitForExit();
this.Visible = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM