Tuesday, July 12, 2016

WinForms C# ctrl-z for undo and redo

I have a personal application I built to help sort pictures. It works really well for me, but no where near commercial quality. Every so often I add a new little feature to it.  This time I'm adding undo and redo.  The control key for handling was a little different than I expected and I had to look it up so I thought I would add it for my own future reference.

        bool bUndoDown = false;

        // checking for ctrl key
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {

            switch (e.KeyCode)
            {

                case Keys.Z:
                    if (bUndoDown)
                        break;

                    if (e.Modifiers == (Keys.Control | Keys.Shift))
                    {
                        bUndoDown = true;
                        Console.WriteLine("redo pressed");
                    }
                    else if (Control.ModifierKeys == Keys.Control)
                    {
                        bUndoDown = true;
                        undodebugcnt++;
                        Console.WriteLine("undo pressed "+undodebugcnt);
                    }
                    break;
            }
        }


    private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (bUndoDown)
            {
                if (e.KeyCode==Keys.Z)
                {
                    bUndoDown = false;
                }
            }
        }

I originally thought I could get this to work with just the KeyPressed event, but had to do it a little deeper in the KeyDown and KeyUp events.

No comments: