Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock/Unlock a windows application form in C#

Tags:

c#

winforms

I need to lock the entire form if the execution of a perticular process is in progress.

My form contains many controls like buttons, comboboxes. all the controls should be in disabled state if the process is running

Now i'n using the two methods from user32.dll

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(String sClassName, String sAppName);

    [DllImport("user32.dll")]
    public static extern bool EnableWindow(IntPtr hwnd, bool bEnable);

but its not working properly.

Is there any other idea to do this

Thanks in advance

like image 767
Thorin Oakenshield Avatar asked Nov 29 '22 05:11

Thorin Oakenshield


1 Answers

What do you mean with lock?

If you want to prevent the user from making inputs you can set

this.Enabled = false;

on you main form, which will disable all child controls, too.

A solution to prevent the events from fireing is to implement a message filter: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.addmessagefilter.aspx and intercept the left mouse button.

// Creates a  message filter.
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class TestMessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        // Blocks all the messages relating to the left mouse button.
        if (m.Msg >= 513 && m.Msg <= 515)
        {
            Console.WriteLine("Processing the messages : " + m.Msg);
            return true;
        }
        return false;
    }
}


public void SomeMethod()
{

    this.Cursor = Cursors.WaitCursor;
    this.Enabled = false;
    Application.AddMessageFilter(new TestMessageFilter(this));

    try
    {
        Threading.Threat.Sleep(10000);
    }
    finally
    {
        Application.RemoveMessageFilter(new TestMessageFilter(this));
        this.Enabled = true;
        this.Cursor = Cursors.Default;
    }


}
like image 87
Jürgen Steinblock Avatar answered Dec 16 '22 18:12

Jürgen Steinblock