Question

Simulating keypress with SendMessage

Asked by: Sys_Prog

Hi,

I am facing a problem simulating a keypress by a sendmessage

I wish to simulate pressing ALT+C to a particcular window

Actually the window has a hyperlink which has a shortcut as ALT+C

I have a handle to that window, and wish to send ALT+C to this window
Hence i tried sending the following messages

                     SendMessage ( handle, WM_SYSKEYDOWN, 18, 540540929) ;            
                  SendMessage ( handle, WM_SYSKEYDOWN, 67, 539885569) ;            
                  SendMessage ( handle, WM_SYSCHAR, 99, 539885569) ;            
                  SendMessage ( handle, WM_SYSKEYUP, 18, -1070071807 ) ;
                  SendMessage ( handle, WM_KEYUP, 67, -1070727167) ;                                          

but it does not work.................If I create a dummy window (using basic SDK programming) and process the keyboard messages writing them to a file, I am able to receieve all these message..........But the messages do not seem to work work on the actual window I want them to work on............ON clicking on the hyperlink OR pressing ALT+C, the window opens a new window

Any help would be greatly appreciated

I posted a similar question (but it was entitlled HOOks, hence posting it again)...

http://www.experts-exchange.com/Programming/Programming_Platforms/Win_Prog/Q_20979995.html

I shall award points for the both the questions to the answerer  

Amit



This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-05-06 at 21:34:09ID20981129
Tags

sendmessage

,

keypress

,

simulate

Topic

Windows Programming

Participating Experts
10
Points
200
Comments
38

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Keyboard Interface to Esc Key in the SDK
    I have an SDK program where I am trying to set things up so that if the user hits the ESC the program terminates. The program is one large parent window with several smaller child window controls. The parent window never really has the keyboard focus. Whenever the parent w...
  2. SendMessage WM_LBUTTONDOWN to another window
    Hello, i want to send a message to another window(program - which i know only it's name - i don't have it's hwnd) this is the code i wrote: SendMessage((long)HWND_BROADCAST,WM_LBUTTONDOWN); Sleep(3000); SendMessage((long)HWND_BROADCAST,WM_LBUTTONUP); like u see - i want ...
  3. wm_char/enter keypress problem
    What is the proper implementation of using SendMessage with the message parameter set to WM_Char in order to send an enter keypress to a text box? Better explanation: I wish to use the WM_Char message in order to send an enter keypress to a text box, therefore successfuly e...
  4. WM_ACTIVATE ???
    Hi, I want to use this code to always set my windows activate, but it doesn't work??? ... Private Procedure ToujoursActif(var Msg :TMessage); message WM_ACTIVATE; ... Procedure TMainForm.ToujoursActif(var Msg :TMessage); begin if Msg.WParam = WA_INACTIVE then Se...
  5. Faking keypress
    Ok, heres my problem. I know i can fake keypressed with WM_KEYUP/DOWN and so, but that does'nt work for apps/games that uses DirectInput to read keys. So my question is if theres any way to write to some sort of keyboard buffer or something to fool DirectInput that a specifi...
  6. Help with Sendmessage
    Hello Experts, Have you ever used WM_KEYDOWN and VK_Key to enter text? I'm trying to use this code: =Module= Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Public ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: drnickPosted on 2004-05-06 at 21:49:22ID: 11012051

hm, it seems to me like you don't have the correct window handle and be sending
the messages to the wrong window.

 

by: Sys_ProgPosted on 2004-05-06 at 21:51:06ID: 11012057

The handle is correct since I can read the title of the window and display the same in a messagebox

Amit

 

by: drnickPosted on 2004-05-06 at 21:52:48ID: 11012063

i think you used something like GetForegroundWindow or EnumWindows to get the handle.

the bad news is, that if i'm right, you got some hide-and-seek to pley.

try to use EnumWindowEx to find all sub windows of your current window handle.
iteratively send your message to the first, second, third and so on window, maybe in a loop
with a delay in it, so you can see when it works.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/Windows/WindowReference/WindowFunctions/EnumChildWindows.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/Windows.asp

 

by: drnickPosted on 2004-05-06 at 21:53:10ID: 11012065

ops, sorry, you were too quick

 

by: drnickPosted on 2004-05-06 at 21:54:16ID: 11012071

hm, however, a window can have sub windows,
and if you send your keystrokes to the parent,
it can happen that they're no processed.
give it a try

 

by: Sys_ProgPosted on 2004-05-06 at 21:55:46ID: 11012075

No, I get the window handle using a global hook
and window does not contain any child controls.......at least it doesn't seem to have

Amit

 

by: drnickPosted on 2004-05-06 at 22:05:33ID: 11012119

hm, strange.

could it be that

SendMessage ( handle, WM_KEYUP, 67, -1070727167) ;      

needs to be

SendMessage ( handle, WM_SYSKEYUP, 67, -1070727167) ;      

?

last thing that comes to my mind (or try changing alls WM_SYSKEY*o WM_KEY* ?)

 

by: Sys_ProgPosted on 2004-05-06 at 22:20:34ID: 11012168

Nope, that is the sequence of messages u get when u actually press ALT+C

Amit

 

by: Sys_ProgPosted on 2004-05-06 at 23:21:38ID: 11012355

I tried sending the Messages for simulating a Mouse click but of no use

Amit

 

by: void_mainPosted on 2004-05-07 at 00:07:26ID: 11012548

I have another aspect:

SendMessage ( handle, WM_KEYUP, 67, -1070727167) ;

what is handle?  or, more exact: where does handle point to?
maybe you sent your messages to the wrong window or to the nirvana...
you can try this:

handle = GetForegroundWindow();

or this

handle = GetDesktopWindow();      // I don't know it the function exist with THIS name ?!?

regards
void_main

 

by: Sys_ProgPosted on 2004-05-07 at 00:28:43ID: 11012635

void_main,

handle points to the destination window
I have confirmed its correct by getting the titke of that window using handle

Also, i am not sure about using GetForeGroundWindow()........Is it necessary that the window should be in ForeGround so that we could send message to that window
I don't think so

Amit

 

by: Sys_ProgPosted on 2004-05-07 at 00:42:09ID: 11012700

Tried with Enum.... method also.....but to no use

amit

 

by: nonubikPosted on 2004-05-07 at 01:46:15ID: 11013023

Maybe we can think another way... Is ALT+C an accelerator to a menu item? If so, you can use a WM_COMMAND message

 

by: SteHPosted on 2004-05-07 at 01:50:11ID: 11013039

I have only used CWnd::PostMessage, but with success.

Have you tried to get a CWnd pointer via CWnd::FromHandle and using that pointer? Either PostMessage or SendMessage.

 

by: nonubikPosted on 2004-05-07 at 01:55:15ID: 11013059

SteH is right, even my SPy++ says it's PostMessage :)

 

by: SteHPosted on 2004-05-07 at 01:55:42ID: 11013061

Another idea: Will the other app recognize the key stroke ony using WM_KEYUP or should you mimic the entire sequence it would get when you press ALT+C:
WM_(SYS)KEYDOWN for ALT, WM_KEYDOWN for C, WM_KEYUP for C, WM_(SYS)KEYUP for ALT. I would think handling should act on xx_KEYDOWN not on keyup.
Or are the calls you gave in the first post that sequence?

 

by: void_mainPosted on 2004-05-07 at 02:31:35ID: 11013199

I am sure you've all looked into a help file. This is from borland c++ builder 6.0:
You don't have to read everything (I copied everything to deliver as much information as possible)
Please look at "remarks"

-----------------------
The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message. The PostMessage function, in contrast, posts a message to a thread's message queue and returns immediately.

LRESULT SendMessage(

    HWND hWnd,      // handle of destination window
    UINT Msg,      // message to send
    WPARAM wParam,      // first message parameter
    LPARAM lParam       // second message parameter
   );      
 

Parameters

hWnd

Identifies the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.

Msg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

 

Return Values

The return value specifies the result of the message processing and depends on the message sent.

Remarks

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.
If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, Windows switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message.
-----------------------

maybe it helps a bit
void_main

 

by: Sys_ProgPosted on 2004-05-07 at 03:05:58ID: 11013337

void_main,

I had read this in msdn.....but it does not help much because as I said, I am able to send messages to a window (created using basic windows SDK programming) and print those messgaes there
But i am not able to simulate the keyboard keypress OR mouse click

 
SteH,

I tried with PostMessage as well......no use
Also, I am not using MFC, hence cannot use CWND::SendMessgae.........I am using the global SendMessage


Amit

 

by: MikProgPosted on 2004-05-07 at 04:26:02ID: 11013631

Fellas! you miss one thing. If you get window caption by window handle it is wrong window to copy/paste it is overlapped/MDI/Dialog window but is not window where you want to get text. handle must be retrieved only GetFocus function. GetFocus gives handle of window where real text is placed. Moreover Did you select text to copy?

 

by: void_mainPosted on 2004-05-07 at 04:32:47ID: 11013661

MikiProg,

i'm sure it was     ALT+C    not    CTRL+C


Sys_Prog,
I found that:
http://www.aivaliotis.com/archives/lv/simulate_keypress.shtml

"its a call from user32.dll and it works on every windows"

have a nice weekend!
void_main

 

by: Sys_ProgPosted on 2004-05-07 at 04:42:21ID: 11013706

MikProg,

THat window is not having k/b focus
Hence GetFocus() wont work (i guess)

Amit

 

by: Sys_ProgPosted on 2004-05-07 at 05:04:01ID: 11013833

void_main,

The link u posted doesn't seem to open on my PC
However, my net connection seems to be quite slow today.
I shall check that link (if it opens) once my net connection gets good

Amit

 

by: SteHPosted on 2004-05-07 at 06:30:52ID: 11014489

Perhaps the article
http://www.codeproject.com/csharp/Automator.asp
can give some insights on how to use user32.dll for simulating key stroke.

PS: I can't get the webpage of M Aivaliotis neither. It seems to be his server.

 

by: SteHPosted on 2004-05-07 at 06:31:45ID: 11014500

And if you are playing with hooks you could try to use the journaling hook to simulate the keystrokes. Just a thought.

 

by: RJSoftPosted on 2004-05-09 at 20:55:47ID: 11028276

If your sure you have the correct handle try using SetActiveWindow or SetFocus then send your keyboard message.

EnumWindows is unreliable unless you know your target is going to have a specific title and/or classname.

I tried to use EnumWindows for controlling ShellExecute untill I discovered WaitForSingleObject thing.. I even use FlashWindow in a loop just to flash a window to prove I had the correct handle.


RJ

 

by: void_mainPosted on 2004-05-09 at 22:20:33ID: 11028534

Okay: Here's the text from the link:

Simulate Keypress

If you've ever wanted to programatically fire a keboard event then I have just the VI for you. This code makes a call to the Windows API calling a function in user32.dll available in all Windows versions. This function allows you to specify any key on the keyboard. When the VI is run, Windows will think the selected key has been pressed.

Looking at the function description available from MSDN we see the following:

keybd_event Function
--------------------------------------------------------------------------------
The keybd_event function synthesizes a keystroke. The system can use such a synthesized keystroke to generate a WM_KEYUP or WM_KEYDOWN message. The keyboard driver's interrupt handler calls the keybd_event function.
Syntax

VOID keybd_event(BYTE bVk,
BYTE bScan,
DWORD dwFlags,
PTR dwExtraInfo
);

Parameters
bVk
[in] Specifies a virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual-Key Codes.

bScan
This parameter is not used.

dwFlags
[in] Specifies various aspects of function operation. This parameter can be one or more of the following values.

KEYEVENTF_EXTENDEDKEY
If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).

KEYEVENTF_KEYUP
If specified, the key is being released. If not specified, the key is being depressed.

dwExtraInfo
[in] Specifies an additional value associated with the key stroke.

Return Value
This function has no return value.


There are two inputs we need to be concerned about. The bScan and dwFlags. For the bScan we need to input the number which represents the key on your keyboard. This number is also available from MSDN. I won't display the complete list since you can retrieve it online from MSDN but I have included the complete list on the diagram of the VI.To make it easier during programming, I've created an enum control for all the possible keyboard values (0-254).

Another input of concern as mentioned above is the dwFlags. This must be toggled between 0 and 2 to indicate that a key is either depressed or released. This is especialy usefull with the ctrl or shift keys. I've created the following diagram and front panel for the above function.


(source:   http://www.aivaliotis.com/archives/lv/simulate_keypress.shtml)


void_main

 

by: MikProgPosted on 2004-05-10 at 21:47:54ID: 11037341

Stop here! When searching answer I loose myself in question. Lets go step by step.

>I wish to simulate pressing ALT+C to a particcular window.................If I create a dummy window (using basic SDK.....
I see you do it well.

>Actually the window has a hyperlink which has a shortcut as ALT+C
Hyperlink is a IHlink COM object that can not have shortcut. Thus shortcut ALT+C is shortcut to anything else that can have shortcuts. How do you realize that?

 

by: Sys_ProgPosted on 2004-05-10 at 22:05:32ID: 11037403

>>Hyperlink is a IHlink COM object that can not have shortcut. Thus shortcut ALT+C is shortcut to anything else that can have shortcuts. How do you realize that?

MikProg,

Just try NetMeeting using MSN Messenger      
Login in to two MSN messenger accounts on two PC's
From one PC, Start a NetMeeting session and select the other users name and click OK
A request would be send to the other user [A window is shown to other user which has Accept/Decline as Hyperlinks which also have k/b shortcuts like ALT+C for Accepting and .......(i dont remember) for Declining

Amit


 

by: MikProgPosted on 2004-05-11 at 00:53:30ID: 11038181

I'm shure in this case ALT-C combo processed elsewhere but not window function. Hot keys are created in windows in several ways. But mostly common is accelerators tables. Native windows application hides accelerators tables deep inside. The main idea of AT is catch keyboard input message, substitute by WM_COMMAND with predefined parameters and send WM_COMMAND to destination. This process takes place inside message loop so the only way is to send messages that emulates keyborad input to thread that owns destination window.

var
  threadid, dw: DWORD;
begin
  threadid:=GetWindowThreadProcessId(Handle,dw);
  PostThreadMessage(threadid,WM_SYSKEYDOWN, 18, 540540929) ;  
... more messages to send to emulate ALT-C
end;
 


 

by: muskad202Posted on 2004-05-11 at 04:28:33ID: 11039290

i think void_main's solution with the keybd_event api is the correct one ... one thing though, that keyb_event sends the keystroke to the window that has the focus, so, before calling keybd_event, u need to call SetForegroundWindow passing the window handle, and then use keybd_event.

 

by: Sys_ProgPosted on 2004-05-14 at 07:36:16ID: 11068689

I tried with keybd_event
                  SetForegroundWindow ( handle ) ;
                  keybd_event ( VK_MENU, 0, 0, 0 ) ;
                  keybd_event ( 'C', 0, 0, 0 ) ;
                  keybd_event ( 'C', 0, KEYEVENTF_KEYUP, 0 ) ;
                  keybd_event ( VK_MENU, 0, KEYEVENTF_KEYUP, 0 ) ;

but to no success

Any ideas

Amit

 

by: fxnutPosted on 2004-05-19 at 02:11:23ID: 11106296

I think keybd_event is depricated now. Try using SendInput instead.

 

by: tkalchevPosted on 2004-05-19 at 06:45:56ID: 11107817

Try

keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), 0, 0);
keybd_event('C', MapVirtualKey('C', 0), 0, 0);
keybd_event('C', MapVirtualKey('C', 0), KEYEVENTF_KEYUP, 0);
keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0)

 

by: muskad202Posted on 2004-05-19 at 10:51:23ID: 11110339

i don't know if the above is correct or not, but i used the following to send and enter key to a window (its kinda simple, coz i didn't have to dela with the menu ... etc --- isn't there a direct shortcut to wht u are trying to do instead of first clcking on the menu ??)

---------
SetForegroundWindow(handle);
keybd_event(VK_RETURN,0,0,0);
---------------

 

by: Sys_ProgPosted on 2004-06-10 at 05:37:43ID: 11278647

Though my actual problem didn't get solved, I did receive some good comments/suggestions

So, an accept is also fine for me

Let me know whether I should accept (i.e. split)

Amit

 

by: VenabiliPosted on 2004-06-17 at 09:36:07ID: 11336381

Sys_Prog ,

You should decide. I would say - make a split :)

Venabili

 

by: void_mainPosted on 2004-06-21 at 00:57:59ID: 11357572

You should look for constuctive posts in this thread an split the points (each post = 200 / num of posts points)

void_main

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...