Using windows message service

Using Messages and Message Queues

The following code examples demonstrate how to perform the following tasks associated with Windows messages and message queues.

Creating a Message Loop

The system does not automatically create a message queue for each thread. Instead, the system creates a message queue only for threads that perform operations which require a message queue. If the thread creates one or more windows, a message loop must be provided; this message loop retrieves messages from the thread’s message queue and dispatches them to the appropriate window procedures.

Because the system directs messages to individual windows in an application, a thread must create at least one window before starting its message loop. Most applications contain a single thread that creates windows. A typical application registers the window class for its main window, creates and shows the main window, and then starts its message loop — all in the WinMain function.

You create a message loop by using the GetMessage and DispatchMessage functions. If your application must obtain character input from the user, include the TranslateMessage function in the loop. TranslateMessage translates virtual-key messages into character messages. The following example shows the message loop in the WinMain function of a simple Windows-based application.

The following example shows a message loop for a thread that uses accelerators and displays a modeless dialog box. When TranslateAccelerator or IsDialogMessage returns TRUE (indicating that the message has been processed), TranslateMessage and DispatchMessage are not called. The reason for this is that TranslateAccelerator and IsDialogMessage perform all necessary translating and dispatching of messages.

Examining a Message Queue

Occasionally, an application needs to examine the contents of a thread’s message queue from outside the thread’s message loop. For example, if an application’s window procedure performs a lengthy drawing operation, you may want the user to be able to interrupt the operation. Unless your application periodically examines the message queue during the operation for mouse and keyboard messages, it will not respond to user input until after the operation has completed. The reason for this is that the DispatchMessage function in the thread’s message loop does not return until the window procedure finishes processing a message.

You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function; both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.

The following example shows how to use PeekMessage to examine a message queue for mouse clicks and keyboard input during a lengthy operation.

Other functions, including GetQueueStatus and GetInputState, also allow you to examine the contents of a thread’s message queue. GetQueueStatus returns an array of flags that indicates the types of messages in the queue; using it is the fastest way to discover whether the queue contains any messages. GetInputState returns TRUE if the queue contains mouse or keyboard messages. Both of these functions can be used to determine whether the queue contains messages that need to be processed.

Читайте также:  Avermedia windows 10 drivers

Posting a Message

You can post a message to a message queue by using the PostMessage function. PostMessage places a message at the end of a thread’s message queue and returns immediately, without waiting for the thread to process the message. The function’s parameters include a window handle, a message identifier, and two message parameters. The system copies these parameters to an MSG structure, fills the time and pt members of the structure, and places the structure in the message queue.

The system uses the window handle passed with the PostMessage function to determine which thread message queue should receive the message. If the handle is HWND_TOPMOST, the system posts the message to the thread message queues of all top-level windows.

You can use the PostThreadMessage function to post a message to a specific thread message queue. PostThreadMessage is similar to PostMessage, except the first parameter is a thread identifier rather than a window handle. You can retrieve the thread identifier by calling the GetCurrentThreadId function.

Use the PostQuitMessage function to exit a message loop. PostQuitMessage posts the WM_QUIT message to the currently executing thread. The thread’s message loop terminates and returns control to the system when it encounters the WM_QUIT message. An application usually calls PostQuitMessage in response to the WM_DESTROY message, as shown in the following example.

Sending a Message

The SendMessage function is used to send a message directly to a window procedure. SendMessage calls a window procedure and waits for that procedure to process the message and return a result.

A message can be sent to any window in the system; all that is required is a window handle. The system uses the handle to determine which window procedure should receive the message.

Before processing a message that may have been sent from another thread, a window procedure should first call the InSendMessage function. If this function returns TRUE, the window procedure should call ReplyMessage before any function that causes the thread to yield control, as shown in the following example.

A number of messages can be sent to controls in a dialog box. These control messages set the appearance, behavior, and content of controls or retrieve information about controls. For example, the CB_ADDSTRING message can add a string to a combo box, and the BM_SETCHECK message can set the check state of a check box or radio button.

Use the SendDlgItemMessage function to send a message to a control, specifying the identifier of the control and the handle of the dialog box window that contains the control. The following example, taken from a dialog box procedure, copies a string from a combo box’s edit control into its list box. The example uses SendDlgItemMessage to send a CB_ADDSTRING message to the combo box.

Show a message box from a Windows Service

Can you display a message box (or any form of notification) from a windows service? Can’t get it to work. I used:

but it didn’t work and just produced an error.

Читайте также:  Windows forms application picturebox

6 Answers 6

No, you cannot show a message box from a service. If you want to report errors, the standard way to do this is with the event log.

For more «advanced» kinds of UI (not just error reporting), the way this is typically done is via a regular windows application that you put in the user’s Startup folder (or the Run key in the registry) and that talks to the service via some kind of IPC mechanism (.NET remoting, WCF, regular sockets, named pipes, etc).

You can display a message from a service with «WTSSendMessage(. )» function (which is available since Windows Vista and Windows Server 2008 ), here is a good article: http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx

Although typically services do not have a user interface, developers can add forms and other UI components. In this case, the «Allow service to interact with desktop» should be checked on the Logon tab in the Service properties dialog (though care should be taken with this approach as this can cause a security risk since any logged in user would be able to interact with the service).

With this option enabled you should be able to display message boxes from a service.

.NET Windows Services (WTSSendMessage) : Displays message on XP but not Windows 7

I have a issue when display a message using .NET window service on Windows 7.It worked properly on Windows XP.I know that it doesn’t work on Windows 7 as explained in Microsoft site and a few forums including Stackoverflow.I have followed the following example(using WTSSendMessage) from Pinvoke.NET as mentioned in the Stackoverflow.But it didn’t work either.that example worked on Windows XP properly.Can some one please help me as this is a really big issue needed to be fixed ASAP since we already migrated to Windows7.

Signature:

Variable declaration:

Code:

4 Answers 4

WTS_CURRENT_SESSION for a service on Windows 7 or later will equate to session 0, which isn’t allowed user interaction. You’ll have to enumerate all the active sessions and send a message to each (which should just be one, unless the computer is running terminal services). Something like the following:

signatures:

helper function:

in your code:

YES it can be done!

I know this is a little late, and this suggestion appears a bit dreadful it actually isn’t: you can ensure that the FIRST currently logged in user is messaged from a service simply by changing the line

this is because since Vista (EG: 2008 , Vista , 2008 R2 , Win7 , Win 2012 , Win 8 , Win 2016 , Win Ten etc) the ID is simply the first logged in user is always 1, the next 2 etc.

Similarly (.. and, therefore) you can ensure the LAST logged in user by doing the reverse, going DOWN the numbers I know it’s naff but you simply loop ints down until you get a non error. You need to go down as the WTSSendMessage calls await a result procedurally (i.e. lock/wait the current thread)

Therefore: a solution whereby you message ALL logged in users (by setting the timeout to zero ) and dispatching to a guesswork of numbers in parallel, via all different threads, and simply ignoring the dead threads.

I use a NuGet package to convert my c# console code to c# service via TopShelf following this tutorial and using the Thread[STAThread] to make sure this works. It will always call the LAST logged in user which in Windows Ten is only ever one person.

Читайте также:  Системе windows не удается получить доступ источникам

in case you’re wondering this does work and the above code is all you need if you’re following the boiler plate TopShelf examples

Message Queuing (MSMQ)

Applies To: Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2, Windows Server Technical Preview, Windows Vista

Purpose

Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues. The following illustration shows how a queue can hold messages that are generated by multiple sending applications and read by multiple receiving applications.

» title=» » data-linktype=»relative-path»/>

Where Applicable

Message Queuing provides guaranteed message delivery, efficient routing, security, and priority-based messaging.

It can be used to implement solutions to both asynchronous and synchronous scenarios requiring high performance. The following list shows several places where Message Queuing can be used.

Mission-critical financial services: for example, electronic commerce.

Embedded and hand-held applications: for example, underlying communications to and from embedded devices that route baggage through airports by means of an automatic baggage system.

Outside sales: for example, sales automation applications for traveling sales representatives.

Workflow: Message Queuing makes it easy to create a workflow that updates each system. A typical design pattern is to implement an agent to interact with each system. Using a workflow-agent architecture also minimizes the impact of changes in one system on the other systems. With Message Queuing, the loose coupling between systems makes upgrading individual systems simpler.

Developer Audience

Message Queuing applications can be developed using C++ APIs or COM objects. Applications can be built in any of the popular development environments: for example, MicrosoftВ® Visual BasicВ®, Visual BasicВ® Scripting Edition, Visual C++В®, Visual StudioВ® .NET, Borland Delphi, and Powersoft Powerbuilder. This allows applications to be developed for the Internet as well, including both server-side (Internet Information Server) and client-side (Internet Explorer) applications. The .NET Framework offers a set of managed Message Queuing objects.

Run-Time Requirements

MSMQ 3.0 can be deployed on computers running Microsoft Windows and members of the Windows Server family.

MSMQ is also available with independent client functionality on computers running Windows CE 3.0.

Interoperability

More information

For information on the following:

New features for each version of Message Queuing. See What’s New in Message Queuing.

Sources of information on installation and administration and books on Message Queuing. See More Information on Message Queuing.

Message Queuing concepts and services. See About Message Queuing.

Examples using API functions and COM components. See Using Message Queuing.

Message Queuing functions, properties, structures, and COM components. See Message Queuing Reference.

Technical terms used in the Message Queuing documentation. See Message Queuing Glossary.

Supplementary information not covered in the body of the Message Queuing documentation. See Message Queuing Appendix.

Оцените статью