Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Reference of keyCodes

    switch (oEvent.keyCode) {
       case 38: //up arrow  
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock
       case 8: //backspace  
       case 46: //delete
           return true;
           break;

       default: 

Note: When capturing combination keys there is dedicated boolean attributes for each of the special keys (CTRL, SHIFT, ALT).
Reference: Make Life Easy With Autocomplete Textboxes [JavaScript & AJAX Tutorials] [sitepoint.com]

Fix double keypress with Safari

Fix a bug with the event keypress ( double keypress ... ) with Safari ( Mac OSX Tiger )
var v_fixDblKey = 0;
function fixDblKey() {
	if (v_fixDblKey != 0) {
		return true;
	} else {
		v_fixDblKey = setTimeout('v_fixDblKey = 0;', 10);
		return false;
	}
}

Sample
...
inputOnkeyup : function(event) {
	if (fixDblKey()) { return; }
	switch (event.keyCode) {
		case 38 : /* up */
			break
		case 40 : /* down */
			break;
		case 37 : /* left */
			break;
		case 39 : /* right */
			break;
		case  9 : /* tab */
			break;
		case 13 : /* enter */
			break;
	}
}
...

javascript window event handling manager

I've seen a lot of window.onload managers, so I generalized it for any window event handler. This assumes prototype.
// BurntoEventManager
// http://brentfitzgerald.com/
// January 2007

var BurntoEventManager = {
    handlers: {},
    add: function(handler_name, method) {
        if(this.handlers[handler_name] == null) {
            this.handlers[handler_name] = new Array();
        }
        this.handlers[handler_name].push(method);
        
        // Now update the window event handler
        window[handler_name] = function(evt) {
            this.handlers[handler_name].each(function(m) {
                m(evt);
            }.bind(this));
        }.bind(this);
    },
    
    clear: function(handler_name) {
        this.handlers[handler_name] = null;
        window[handler_name] = function() {};
    },
    
    get: function(handler_name) {
        return this.handlers[handler_name];
    }
}

For example, consider if later on in our application we want to add an onclick handler.
BurntoEventManager.add("onclick", function(evt) { alert(evt) });

Python - Example Simple ImageView

import pygtk; pygtk.require('2.0')
import gtk

class Image_Example(object):

	def pressButton(self, widget, data=None):
		print "Pressed"

	def delete_event(self, widget, event, data=None):
		print "delete event occured"

		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("delete_event", self.delete_event)
		self.window.connect("destroy", self.destroy)
		self.window.set_border_width(10)

		self.button = gtk.Button()
		self.button.connect("clicked", self.pressButton, None)
		self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

		self.image = gtk.Image()
		self.image.set_from_file("/tmp/f27.jpg")
		self.image.show()

		self.button.add(self.image)
		self.window.add(self.button)
		self.button.show()
		self.window.show()

	def main(self):
		gtk.main()


if __name__ == '__main__':

	Image_Example().main()

Python - Mouse Capture

// Minimo Esempio di pannello con evento

import wx

class MyFrame(wx.Frame):
    
    def __init__(self):
        
        # creo un frame
        wx.Frame.__init__(self, None, -1, 'My Frame', size=(300, 300))
        # aggiungo un pannello
        panel = wx.Panel(self, -1)
        # aggiungo un evento al pannello
        panel.Bind(wx.EVT_MOTION, self.OnMove)
        # aggiungo un controllo di testo
        self.posCtrl = wx.TextCtrl(panel, -1, 'Pos: ', pos=(40, 10))
        
    def OnMove(self, event):
        
        # catturo la posizione del mouse
        pos = event.GetPosition()
        # scrivo tale posizione nel controllo di testo
        self.posCtrl.SetValue('%s, %s' % (pos.x, pos.y))
        
if '__main__' == __name__:
    
    app = wx.PySimpleApp()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

Handle keyboard event easily

I found a code that simplify keyboard event handling
from the popular pys60 tutorial.
I simplify it a bit (removing some feature but make it easier to read)
from appuifw import *
from key_codes import *

class Keyboard(object):
    def __init__(self):
        self.state = {}  # is this key pressing ?
        self.buffer= {}  # is it waiting to be processed ?
    def handle_event(self, event): # for event_callback
        code = event['scancode']
        if event['type'] == EEventKeyDown:
            self.buffer[code]= 1   # put into queue
            self.state[code] = 1
        elif event['type'] == EEventKeyUp:
            self.state[code] = 0
    def pressing(self, code):      # just check
        return self.state.get(code,0)
    def pressed(self, code):       # check and process the event
        if self.buffer.get(code,0):
            self.buffer[code] = 0  # take out of queue
            return 1
        return 0

key = Keyboard()
app.body = canvas = Canvas(event_callback=key.handle_event)

Now you can check the keyboard status with key.pressing and key.pressed
>>> key.state   # just pressed up arrow
{17: 0}
>>> key.buffer
{17: 1}
>>> key.pressing(EScancodeUpArrow)  # it's not pressing
0
>>> key.pressed(EScancodeUpArrow)   # yes, it's pressed
1
>>> key.pressed(EScancodeUpArrow)   # no, you've just processed it
0
>>>

double-click event snippet

; event/double-click
view layout [
	box "A Box" forest rate 1 feel [
		engage: func [face action event] [
			print [ action event/type]
			if action = 'down [
				print event/double-click
			]
		]
	]
]

Watch key events snippet

view/new layout [
	the-box: field "A Box" forest feel [
		engage: func [face action event] [
			if action = 'key [
				either word? event/key [
					print ["Special key:" event/key]
				][
					print ["Normal key:" mold event/key]
				]
			]
		]
	]
]
focus the-box
do-events

Getting key press

In Pys60 1.2 there are 3 types for app.body, namely
- Canvas
- Text
- Listbox
They can recieve and process key press.
In older versions, they all have a bind method:
bind(event_code, callback)

event codes are defined in key_codes module
You can import some or all of them
from key_codes import EKeyLeftArrow, EKeySelect, EKey9, EKeyEdit
See diagram for 6630.

In the latest version, Canvas gains ability to respond
to events in more details. You can give it 2 callbacks
when creating a Canvas object.
c = Canvas(redraw_callback=None, event_callback=None)

event_callback will get a dict of the key event containing:
- 'type': one of EEventKeyDown, EEventKey, or EEventKeyUp
- 'keycode': the logical key
- 'scancode': the physical key
- 'modifier': probably about Shift, Ctrl ?

The simplest use is to detect when type=EEventKey
and use the 'keycode' value.
For advanced use, look at keyviewer.py example.
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS