# use multiple keys in C



## ayush_chh (Aug 26, 2008)

hi guys!

How can i use multiple keys in C?  i am doing a graphics project. my aim is to move an object from one place to other. for moving to left, right, up and down we can use directional keys. this i have already achieved.

Now i want to move the same object in diagonal direction using multiple keys.
For Eg.:- if i press left and up arrow keys together the object should move to  top left corner.

Note:- If the query is not clear then pls reply. do not ignore. Pls help me.


----------



## QwertyManiac (Aug 26, 2008)

If both keys (1,2) are pressed down:
    # Keep increasing both X and Y co-ords of the object by each unit step. (ie) (9,9) becomes (10,10), now repaint.
    # OR
    # First move one step in 1's direction
    # Second move one step in 2's direction
Repeat

This would be the general idea I suppose. I do it this way in Qt...


----------



## Bandu (Aug 27, 2008)

I don't think that you will ever get a distinct keycode when 2 keys are simultaneously pressed (I might be wrong though). You should first try to output the keycodes that you receive and see if you get a different one when both are pressed.

Instead try using a different key altogether for your diagonal movement.


----------



## ayush_chh (Aug 28, 2008)

@qwertymaniac

can you pls give me the actul code coz when i use the codes it doesn't work


```
if(key==77 && key==80)//key is the variable thats gets the ascii of the key pressed
{

}
```

this doesn't work


@bandu

how to game developers achieve this then? is there no possibility in C?


----------



## dheeraj_kumar (Aug 28, 2008)

Game devs do it using directinput. I havent tried it but that code should NOT work, as a variable cannot equal to two operands(lol, think, think) but you can try this:

if(key == (87 && 79) )

using logical and operator.


----------



## Bandu (Aug 28, 2008)

> @bandu
> 
> how to game developers achieve this then? is there no possibility in C?


 
Is there a freely available C compiler that I can quickly download and try all this myself?

I found a free copy of TC 2.0 and quickly worked out a small program to test these things.
Here's what I wrote:

```
#include <conio.h>

int main()
{
	int myKey;
	clrscr();
	printf("Press q to quit");
	do
	{
		if(kbhit())
		{
			myKey = getch();
			switch(myKey)
			{
				case 72: printf("\nMove to top");
					break;
				case 75: printf("\nMove to left");
					break;
				case (72 && 75): printf("\nMove to top-left");
					break;
				case 113: return 0;
			}
		}
	} while(1);
}
```

As I suspected, you either get a left or a top key press event (the latest that was pressed) and not both - neither a && nor || Nothing.

As for your question - I think the Game devs use some other way to determine simultaneous key press - directinput or some such thing.

If you can elaborate on what exactly you are using (directinput, GDI, etc.), then maybe I can try something more.

- Bandu.


----------



## QwertyManiac (Aug 29, 2008)

I use a key state list of 4 boolean values, and switch them T/F at each valid keypress event and keep calling the function that works on them. At the same time it would not work, unless you are also using a modifier...


----------



## dheeraj_kumar (Aug 29, 2008)

> case 72: printf("\nMove to top");
> break;
> case 75: printf("\nMove to left");
> break;
> ...



@bandu, try :

case (72 && 75): blah blah; break;
case 72: blah; break;
case 75: blah; break;


----------



## Bandu (Aug 29, 2008)

@harsh: I have no idea about key state list. Can you post your snippet?

@dheeraj: Have a look at my code snippet above. It does have 
	
	



```
case (72 && 75): printf("\nMove to top-left");
```
. I never get to see the _Move to top-left_ output.

- Bandu.


----------



## QwertyManiac (Aug 29, 2008)

I don't know how a logical AND would work out, bitwise AND *&* (OR *|* more like) could make some sense but logical? It always returns 0 or 1...

Here's my snippet in Python and Qt (PyQt4 module's required if you wanna execute it):

```
from PyQt4 import QtCore, QtGui
from sys import argv

class MyWidget(QtGui.QWidget):
	def __init__(self):
		QtGui.QWidget.__init__(self)
		self.directions = {
		[B]QtCore.Qt.Key_Up:[False,"Up"],
		QtCore.Qt.Key_Left:[False, "Left"],
		QtCore.Qt.Key_Down:[False, "Down"],
		QtCore.Qt.Key_Right:[False, "Right"][/B]
		}
		self.dims = [0,0,10,20]
		self.rect = QtCore.QRect(*self.dims)
		self.painter = QtGui.QPainter()

	def updateKeys(self, button, value):
		self.directions[button][0]=value

	def callFunc(self):
		a=""
		for each in self.directions:
			if self.directions[each][0]==True:
				if self.directions[each][1]=="Left":
					self.dims[2]-=5
				elif self.directions[each][1]=="Right":
					self.dims[2]+=5
				elif self.directions[each][1]=="Up":
					self.dims[3]-=5
				else:
					self.dims[3]+=5
		self.rect = QtCore.QRect(*self.dims)

	def paintEvent(self, event):
		self.painter.begin(self)
		self.painter.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush))
		self.painter.setPen(QtCore.Qt.SolidLine)
		self.painter.drawRect(self.rect)
		self.painter.end()

	def keyPressEvent(self, event):
		if event.key() in self.directions:
			self.updateKeys(event.key(),True)
			self.callFunc()
		QtGui.QWidget.keyPressEvent(self, event)
		self.update()

	def keyReleaseEvent(self, event):
		if event.key() in self.directions:
			self.updateKeys(event.key(),False)
			self.callFunc()
		QtGui.QWidget.keyPressEvent(self, event)
		self.update()

app=QtGui.QApplication(argv)
a=MyWidget()
a.show()
app.exec_()
```

The bold part indicates the key-state list. I've used a dict, for easiness and readability but you can use a simple bool array too.


----------



## Bandu (Aug 29, 2008)

@Harsh - You are right - logical && does not make sense. But, a bitwise & also does not work in this case.

I could install Turbo C, but am not sure about Python.

What would you get if you add a printf (or similar thing) in your def keyPressEvent(self, event) and press both the key simultaneously? What would get printed?


----------



## QwertyManiac (Aug 29, 2008)

keyPressEvent is an overloaded function here (Qt, much like Java's own AWT?), whenever a key is pressed on the keyboard while the Widget is the active window, the keyPressEvent()'s contents are executed.

Let me show it in parallel, with a print and the window. Its gonna be quite some amount of screenshots:

On start, the default rect of 10x20 at (0,0) is drawn, as per the code above. Each keypress makes a change of 5 pixels in this case.
*img397.imageshack.us/img397/5952/initialfm4.jpeg

On one keypress:
*img397.imageshack.us/img397/7509/onebuttonxg2.jpeg

On two keypresses:
*img397.imageshack.us/img397/3456/twobuttonsbr8.jpeg

Again, on two different keypresses:
*img397.imageshack.us/img397/1349/twobuttons2ee5.jpeg

Total output on the terminal via print, as you asked: 

```
Right                          

Right                                                          
RightDown                                                      
Right                                                          

Up
LeftUp
Up
```

3 values appear because the input is sent one by one and the same's at removal. That is not an issue or anything


----------



## ayush_chh (Aug 29, 2008)

@dheeraj

thankyou for making me think.....the logical AND won't work tha's for sure

i thought of one more method

when the right key is pressed the control goes to one more while loop where i can check for next key(up or down) and then use it.

i found some values on net like (45) can be used for (Alt+X)....how is that possible?? coz 45 is ascii code for '*-*'


----------



## QwertyManiac (Aug 29, 2008)

ayush_chh - Cause ALT/CTRL/SHIFT/META/etc keys are known as modifier keys. They modify the general behaviour and values (OR/XOR?) of the keys they are used with.


----------



## dheeraj_kumar (Aug 31, 2008)

Windoze has something perfect for this called GetKeyboardState, but unfortunately its win32 api. 

Do you know if dos supports multiple keypresses? that depends on the OS(I think), like windows does only 3 keypresses simultaneosly.


----------



## QwertyManiac (Aug 31, 2008)

Yep only 3


----------



## ayush_chh (Sep 1, 2008)

thanks a lot for the replies .... that was informative..

i have decided to use num - pad for the control now.....


----------



## QwertyManiac (Sep 1, 2008)

With the set/reset array I hope? So that two keypresses are usable?


----------



## ayush_chh (Sep 1, 2008)

what is this Set/reset array?


----------



## QwertyManiac (Sep 1, 2008)

Its the same as your multiple loop idea, and what I've demoed above.


----------

