How to block a form after certain downtime?

Asked

Viewed 1,166 times

2

Example: After 1 minute of inactivity the 'system' form is disabled and calls a 'login' form, after completing the login it returns to the 'system' form and activates it again..

Or it can be by pressing a button it blocks the 'system' form and calls 'login', when you login it activates the form again..

I tried to disable the this.Enabled of the current form after clicking the lock button and after that creating an instance of 'login' and opening it, in logic the command to unlock the form 'system' would be to click the login button, after the name and password checks, but I can’t access the property .Enabled system form by login.. I tried to create a static variable to control this, but it doesn’t work because I don’t have an Update function that updates every second (as in Unity) and I don’t know how to create this function in Visual Studio

  • Can you share the code structure? Have you tried Timer?

  • try IEnumerator I think it should work.Example

  • I got it here, but it only records click or modification of the fields as activity, mouse movement is discarded, ie if the user is just moving the mouse in the form, when it reaches the team it will block.. I’ll post the code I used here

2 answers

1


If you want to reset your iddle time (namely, your Timer) in the movement of the mouse or in the keystroke of the button, consider:

Form1.cs

    public Point mouseLocation;
    public static LoginBloq nvLoginBloq = new LoginBloq(); 

    public Form1()
    {
        InitializeComponent();

        this.KeyPress += _keyPress;
        this.MouseMove += _mouseMove;
    }

    private void _mouseMove(object sender, MouseEventArgs e)
    {
        mouseLocation = e.Location;
        this.ResetaIddleTimer();
    }

    private  void _keyPress(object sender, KeyPressEventArgs e)
    {
        this.ResetaIddleTimer();
    }

    void ResetaIddleTimer()
    {
        // código para resetar o iddle time
    }

Note that LoginBloq is created only once in Form1.cs and is static. According to the flow of your code, you can control the visibility of nvLoginBloq of any other form:

OutroForm.cs

public partial class OutroForm : Form
{
    public OutroForm()
    {
        InitializeComponent();

        Form1.nvLoginBloq.Visible = true;

    }
}

I mean, this way you centralization the control of iddle time and at the same time access to LoginBloq in one class (Form1).

  • It worked, just could not create the instance as public Static, because it was giving conflict.. So, a splash screen opens login instance, this instance opens another 'interface' instance at the start (because I need it to be public Static, to lock and unlock).. then the visual does not allow creating another public and statistical instance when starting another form.. So I created an instance as it was.. It worked good to capture mouse movement

  • Can I 'destroy' the instance? Like, after it authenticates the login in nvLoginBloq, is there any way to destroy this nvLoginBloq? thus erasing it and not creating instance after instance

  • @Leonardovilarinho, I’m glad it worked. static does not allow to create other instances even, this is the advantage, is a global instance that allows only to change the properties, etc. Want a hint? Create a method public static Init() {} in his Form1.cs and within it seven all you need, including the first and only instance of LoginBloq! Who should call her? Her SplashScreen.cs: Form1.Init(). Including EU particularly Gero all Forms once (or Pages in the case of WPF) using a method static in my Form1 (or Mainwindow, in the case of WPF).

  • yes, like I didn’t create another instance of nvLogin or nvInterface (which is the two static instances).. The IDE even compiles, but when it executes it error the static instance created by nvLogin (it is within a static instance of nvFormulario that is within a common instance of the main login screen).. These static instances are created after the creation screen of the main login instance... I didn’t understand the IDE error '-'

  • How you would be creating these instances, I can see?

  • Login nvLogin = new Login(); in the form of Splash -- public static Interface nvInterface = new Interface(); in form nvLogin (to be able to control time and availability) -- LoginBloq nvLoginBloq = new LoginBloq(); in form nvInteface.. This way is no mistake, but is instantiating the nvLoginBloq, when placing public static LoginBloq nvLoginBloq = new LoginBloq(); in form nvInteface it gives the error.. But I managed to fix here, instantiating statically the nvLoginBloq in the nvLogin and changing form codes (to clear Texts box after authenticating login etc )

  • So it worked? Well, I think for your purpose, the ideal is to keep a single instance of all the Foms! But I’m glad you made it!

  • I am facing a problem with your code, it just resets the counter while I have clicking or passing the mouse on form properly said, if I keep passing the mouse in the menustrip or on some panel, it calls the form login even with mouse movement, it complicates.

  • Oops! This is simple to solve. If you keep the methods _mouseMove and _keyPress public and static in Form1.cs, then it is sufficient that in each form your, you record these events. Ex.: FormNovo.cs (in the builder): this.KeyPress += Form1._keyPress;
 this.MouseMove += Form1._mouseMove;

  • The most important thing is centralize ALL repetitive actions in your code suddenly create even a static class just for this (until recommended), example: IddleState.cs. Anyway, Leonardo, EACH FORM OF YOURS will have to register the events this.KeyPress and this.MouseMove and inform the methods in one place (yes, because imagine each form having its own methods _keypress and _Mousemove?)

  • Other detail: The Timer also needs to be in one place (and be static, recommended), for example, in the Form1.cs for ALL to share the same counter and only one to be reset, etc.

  • If the answer was valid, please consider marking it!

  • Did not even change to publish and static, the panel and menu is in the same form as these events, example, the code only works while the mouse is in the area that the arrow comes in contact with the background of the main form, when the arrow is in contact with another object of the form (like button, panel, menu, image, etc.) and you are moving the mouse there in those objects the code does not work, after a while the Login is called, even with the mouse in motion,, I tried taking the this. but continued the error

  • Each form of yours is with registered mouse and keyboard events? Where is the counter (Timer)?

Show 9 more comments

0

Well achieved, there is only one drawback, it does not record mouse movement as activity, just click, changing fields, etc.. The code is big:

Form 'system'

public Timer relogio; // cria timer
public int contador = -1; // contador (conta o tempo em segundos)
public bool atv = false; // booleano para controle do formulario de login

// abaixo do InitializeComponent();
relogio = new Timer(); // cria uma instancia de time
relogio.Interval = 1000; //depermina o tempo (assim fica em segundos)
relogio.Enabled = true; // ativa o time
this.relogio.Tick += new System.EventHandler(this.relogio_Tick); // cria um metodo de controle

private void Interface_Click(object sender, EventArgs e)
{//redefine contador quando há clique no formulario (deve-se criar isso para cada campo de formulario, desde menu a campos de texto)
    contador = -1;
}

private void relogio_Tick(object sender, EventArgs e) //controlador de time
{
    if (contador == 10) // quando o contador chegar a 10 (10 segundos)
    {
        if (atv == false)//se a tela de login nao estiver em execução
        {
            this.Enabled = false;//desabilita o formulario 'sistema'
            LoginBloq nvLoginBloq = new LoginBloq(); //cria uma instancia do login
            nvLoginBloq.Show(); // abre a instancia
        }
        else{}//se atv = true (se formulario 'login' estiver ativo não faz nada)
    }

    else if(contador > 10) //se contador for mais que 10 (10 segundos)
    {
        this.relogio.Enabled = false;//desabilita relogio
    }
    contador++;// a cada vez ele que executa o metodo (sempre) ele aumenta contador
}

Form 'login'

//após o InitializeComponent();
Login.nvInterface.atv = true; // fala que esta ativo (para nao ficar criando novos form 'login')

// após ele permitir o login (ao clicar no botao de login)
this.Enabled = false; // desabilita a si mesmo
Login.nvInterface.atv = false; //
Login.nvInterface.contador = -1; //rededine o contador (em segundos)
Login.nvInterface.relogio.Enabled = true; //ativa o time novamente
Login.nvInterface.Show(); //mostra novamente o formulario 'sistema'
Login.nvInterface.Enabled = true; // ativa (desbloqueia) formulario 'sistema'
this.Visible = false; // torna-se invisivel
//as linhas Visible e Enabled, são necessárias nessa ordem, se não ele buga

Login.nvInterface - is an instance created in another Login form (the main one), to display the 'system' form'

If you have any form before the 'system' (as is the case)

Previous form

// antes de tudo
public static Interface nvInterface = new Interface(); //criar uma instancia publica do formulario 'sistema'

// depois de InitializeComponent();
nvInterface.relogio.Enabled = false; //desativa relogio do formulario 'sistema'

// no metodo do botão que vai para o formulario 'sistema' ou depois do InitializeComponent(); do formulario 'sistema'
nvInterface.relogio.Enabled = true; //ativa relogio do formulario 'sistema'

// assim ele 'trava' o time da instancia ate que ela seja exibida
  • LoginBloq is instantiated every time? I would do this once only in the main form and only control visibility, @Leonardo Vilarinho

  • Yes it is instantiated every time the screen 'blocks' or the user clicks on the lock button.. I thought he would replace what is instantiated currently, by creating one with the same name, I’m still new to this.. But if I instantiate only one and control visibility, at some point it wouldn’t give a bug (because it takes file information and compares with what the user typed)?

  • Opa! Wouldn’t give bug no, because the function of static is the same! Non-static elements are "new" elements (with keyword new), and not elements that hold the same. The advantage is that maintaining a LoginBloq nvLoginBloq in the main form, it is possible to take it from any other form and on top of that it does not need a new instantiation. If your application still focuses on UI with visual elements, effects, etc, consider using WPF, i love WPF. It’s the C# most "visual".

  • Once I had to work with the same goal as yours: iddle time. I made a counter the same way you did. As it was an application for totem (those self-service PC) the iddle time was reset only when the user did something (touched a button, for example). In your case, if you need to check if the mouse has been moved, see my answer below.

  • I had never seen this WPF (the desing created just changing the properties in Visual Studio) until it was cool, I just wanted transparency in the background (which I could not do)

  • Opa, dá sim, you can use a background with opacity! It’s almost a CSS. But we can not extend other conversations here, it is against the regulation hehe hug!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.