8 Replies - 22435 Views - Last Post: 26 January 2011 - 05:20 PM Rate Topic: -----

#1 nidhish31588   User is offline

  • New D.I.C Head

Reputation: -11
  • View blog
  • Posts: 15
  • Joined: 07-August 09

how to press and release a form button through keyboard?

Posted 26 January 2011 - 06:41 AM

hey anyone please help me.............

can anyone tell me how to press a button through a keyboard key.....i.e for example if i'm pressing a key (e.g 'A'),the button in the form should be pressed and perform its task.....and also on releasing the key(i.e 'A'), the task of the button should end......(just like the piano ,on pressing a key the sound comes, and on releasing the sound stops)



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PROJ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.Visible=true;
        }


    }
}




in the above code, i want to click the button1 through a keyboard key....on pressing the Form2 should appear and simultaneously on releasing the key the Form1 should disappear.......

Is This A Good Question/Topic? 0
  • +

Replies To: how to press and release a form button through keyboard?

#2 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 08:30 AM

First of all, that's not how clicking a button works. "Click" is only fired when there's a MouseDown followed by a MouseUp. If you want one action taken on the "Down" and a different one on the "Up", then you'll have to handle those events individually, not just the Click event.

And you'll also need to handle the Form's KeyDown and KeyUp events. Check which key was pressed, and if it's the correct key, perform the action.

The best way to achieve this is to write two methods. One to do the action you want on "Down", and one to do what you want on "Up." Then, in the event handlers for both the keys and the mouse events, call these methods you wrote. That way you don't have to duplicate code.
Was This Post Helpful? 1
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 08:41 AM

It would be better to fix your style of coding that try to call button_click event handler through a keyboard.

You really shouldn't put the functionality in the click event handler. Instead have the click call the method that does the work.
Then you can have the keyboard event also call the same method.
Or you can have a dozen other things call that same method.

Below we see a minor rewrite where a button, a menu, and a context menu all have options for making a new form. All of those handlers call the same MakeNewTwo() method.

namespace PROJ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MakeNewTwo();
        }

        private void NewFormMenuItem_Click(object sender, EventArgs e)
        {
            MakeNewTwo();
        }

        private void ContextMenuNewItem_Click(object sender, EventArgs e)
        {
            MakeNewTwo();
        }



        void MakeNewTwo()
        {
            Form2 f = new Form2();
            f.Visible=true;
        }




    }
}





Moving on to the second part of your question

Quote

on pressing the Form2 should appear and simultaneously on releasing the key the Form1 should disappear.......

Form.Show() and Form.Hide()
So when your make a new Form2 you would then perform this.Hide(); from inside Form1.

I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard - or you can learn by doing the tutorials and following a good "How to learn C#" book.

May I suggest picking up a basic C# introductory book? It's not that people here don't want to be helpful, but there is a certain amount of basic learning work that one should really take upon themselves before asking for help. There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" books at your local book seller or even public library.

C# resources. Start here

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Quick and easy custom events
Bulding an application - Part 1
Building an application - Part 2
Debugging tutorial
Working with environmental variables

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

  • Anonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity.
  • Arrays: Shows how to use arrays.
  • Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection.
  • Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement.
  • COM Interop Part I: Shows how to use C# to interoperate with COM objects.
  • COM Interop Part II: Shows how to a use a C# server together with a C++ COM client.
  • Commandline: Demonstrates simple command-line processing and array indexing.
  • Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined.
  • Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates.
  • Events: Shows how to declare, invoke, and configure events in C#.
  • Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances.
  • Generics: Shows how to make generic collection classes that can be used with the foreach statement.
  • Hello World: A Hello World application.
  • Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects.
  • Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection.
  • Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs
  • Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads
  • Nullable: Demonstrates value types, such as double and bool, that can be set to null
  • Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0
  • OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it.
  • Operator Overloading: Shows how user-defined classes can overload operators
  • Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files
  • PInvoke: Shows how to call exported DLL functions from C#
  • Properties: Shows how properties are declared and used; also demonstrates abstract properties
  • Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0
  • Security: Discusses .NET Framework security and shows how to modify security permissions in C# by using permission classes and permission attributes
  • Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates
  • Structs: Shows how to use structs in C#.
  • Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool
  • Unsafe: Shows how to use unmanaged code (code that uses pointers) in C#
  • User Conversions: Shows how to define conversions to and from user-defined types
  • Versioning: Demonstrates versioning in C# by using the override and new keywords
  • XML Documents: Shows how to document code by using XML
  • Yield: Demonstrates how to use the yield keyword to filter items in a collection

Was This Post Helpful? 1
  • +
  • -

#4 nidhish31588   User is offline

  • New D.I.C Head

Reputation: -11
  • View blog
  • Posts: 15
  • Joined: 07-August 09

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 10:57 AM

even still not working.............

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PROJ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
        protected override void onkeydown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                Form2 fo = new Form2();
                fo.Visible = true;
                fo.Show();
            }
        }
        protected override void onkeyup(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                Form2 fo = new Form2();
                fo.Visible = false;
                fo.Hide();
            }
        }
    }
}




Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 11:05 AM

Give us something to go on

Debugging tutorial

But you're just not grasping the basics here. In each method you are making a NEW form, then hiding that. How are you expecting that to look like anything.

You should start with an into to C# book and work through the tutorials instead of just banging on the keyboard. Many good resources were already given to you. If you don't want to follow them that's your business. But there are 100,00 users on here and probably 500 newbies joining every day. You can't really expect the experts here to handhold every one of them through their "How do I make my first 'Hello World' application?". You need to take responsibility for your own education and pick up a book.
Was This Post Helpful? 0
  • +
  • -

#6 nidhish31588   User is offline

  • New D.I.C Head

Reputation: -11
  • View blog
  • Posts: 15
  • Joined: 07-August 09

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 04:45 PM

please help me...........since i want this code to complete my major project............
Was This Post Helpful? -5
  • +
  • -

#7 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 04:51 PM

Nobody's going to write this code for you. We've given you the suggestions you need to at least try again. I already told you you'll need to handle the button's MouseUp and MouseDown events and the form's KeyUp and KeyDown events if you're going to do this. And you need to write a method that actually does what you want on the down action, and one that does what you want on the up action. You'll need to do each of those things, and then let us know if it works or not.
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 05:11 PM

View Postnidhish31588, on 26 January 2011 - 04:45 PM, said:

please help me...........since i want this code to complete my major project............

Let's take another approach at explaining this to you. You don't have enough understanding of C# or Windows.Forms to be able to write what you want. And you seem unwilling to do what everyone else has done: Start at the beginning and *learn* before trying to *write*.

Let me point out one example so you can hopefully start to understand how much you don't understand.

        protected override void onkeydown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                Form2 fo = new Form2();
                fo.Visible = true;
                fo.Show();
            }
        }
        protected override void onkeyup(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                Form2 fo = new Form2();
                fo.Visible = false;
                fo.Hide();
            }
        }
    }
}


Line 6 - Unneeded because you are using .Show and Hide. .Visible is property that causes the .Show() and .Hide() methods to be executed. It's redundant.

Your onkeyup() method is totally pointless. Line 14 makes a completely new instance of a Form2 object. This is NOT the same Form2 that you created in the onkeydown() method. Two different Form2 instances. Its just like my Dodge Ram is a different instance of the Dodge Ram object type, than the identical looking Dodge Ram that my neighbor has. Hiding or showing my Dodge Ram in no way affects the visibility of my neighbor's Dodge Ram.

You might as well be saying that you need someone to teach you how rebuild a car engine 2 days before your driver's test, but you've never lifted a car hood. Or saying "I have a big concert on Friday. Can you teach me to play the piano?"

You need to pick up any of the 'My first program' books and start at page 1 and work through the lessons. Or any of the numerous teach tutorials on the 'net. This isn't the Matrix where we can just download the ability to write code into your head through a forum thread.

Nobody is saying you can't learn it. Nobody is saying you're incapable. Just that you actually need to learn from the beginning. Crawl, then walk, then run.
Was This Post Helpful? 1
  • +
  • -

#9 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: how to press and release a form button through keyboard?

Posted 26 January 2011 - 05:20 PM

Also, neither of those methods match event handler method signatures.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1