473,583 Members | 2,878 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem implementing a message loop

I am trying to write an event-driven application with no main window that
runs "forever". It waits on a named event and then displays a window
depending on data pased in a memory-mapped file. I started with a standard
console application and it all works fine, except that it does not terminate
tidily when the user logs off/shuts down. So, I figured I needed a message
loop to pick up WM_QUIT. I studied the code in "Waiting in a message loop"
(http://msdn.microsoft.com/library/de...ssage_loop.asp) and implemented it in my Main(), using
MsgWaitForMulti pleObjects(1, handles, false, INFINITE, QS_POSTMESSAGE +
QS_SENDMESSAGE) ;
to wait for either my named event (in 'handles') or a windows message. The
event fires fine, but no windows messages ever arrive. I am obviously doing
something wrong, Can anyone advise.
--
Dave
May 29 '06 #1
8 5245

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:21******** *************** ***********@mic rosoft.com...
|I am trying to write an event-driven application with no main window that
| runs "forever". It waits on a named event and then displays a window
| depending on data pased in a memory-mapped file. I started with a standard
| console application and it all works fine, except that it does not
terminate
| tidily when the user logs off/shuts down. So, I figured I needed a message
| loop to pick up WM_QUIT. I studied the code in "Waiting in a message loop"
|
(http://msdn.microsoft.com/library/de...ssage_loop.asp)
and implemented it in my Main(), using
| MsgWaitForMulti pleObjects(1, handles, false, INFINITE, QS_POSTMESSAGE +
| QS_SENDMESSAGE) ;
| to wait for either my named event (in 'handles') or a windows message. The
| event fires fine, but no windows messages ever arrive. I am obviously
doing
| something wrong, Can anyone advise.
| --
| Dave

This will not work, you need a main windows for the system to post/send
messages to, you just need to handle the SessionEnded event on the
Microsoft.Win32 .SystemEvents class.

Willy.
May 29 '06 #2
Thanks Willy, but if I implement it as a Windows app with a main window,
execution then disappears into the main window (ie the main window's message
loop) so how do I then wait for my named event?
--
Dave
"Willy Denoyette [MVP]" wrote:

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:21******** *************** ***********@mic rosoft.com...
|I am trying to write an event-driven application with no main window that
| runs "forever". It waits on a named event and then displays a window
| depending on data pased in a memory-mapped file. I started with a standard
| console application and it all works fine, except that it does not
terminate
| tidily when the user logs off/shuts down. So, I figured I needed a message
| loop to pick up WM_QUIT. I studied the code in "Waiting in a message loop"
|
(http://msdn.microsoft.com/library/de...ssage_loop.asp)
and implemented it in my Main(), using
| MsgWaitForMulti pleObjects(1, handles, false, INFINITE, QS_POSTMESSAGE +
| QS_SENDMESSAGE) ;
| to wait for either my named event (in 'handles') or a windows message. The
| event fires fine, but no windows messages ever arrive. I am obviously
doing
| something wrong, Can anyone advise.
| --
| Dave

This will not work, you need a main windows for the system to post/send
messages to, you just need to handle the SessionEnded event on the
Microsoft.Win32 .SystemEvents class.

Willy.

May 29 '06 #3

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:C1******** *************** ***********@mic rosoft.com...
| Thanks Willy, but if I implement it as a Windows app with a main window,
| execution then disappears into the main window (ie the main window's
message
| loop) so how do I then wait for my named event?
| --
| Dave
|
|
| "Willy Denoyette [MVP]" wrote:
|

Sorry if I wasn't clear, point is that you don't need a main windows (a Form
instance), all you need is a message pump to handle this.
You can start a separate thread to handle your main task before you start
the message loop by calling Application.Run ().

Something like this should do:
[STAThread]
static void Main()
{
SystemEvents.Se ssionEnded += new
SessionEndedEve ntHandler(Sessi onEnd);
// Start a new backgound thread to handle your main task here.
// Start a message pump.
Application.Run ();
}
static void SessionEnd(obje ct s, SessionEndedEve ntArgs e)
{
...
}

Willy.
May 29 '06 #4
Hi Willy
I was confused there as your original reply said "you need a main windows".
I have implemented the event (I used SessionEnding rather than SessionEnded)
but it still doesn't work - when I log off the SessionEnding event is never
fired, but I get a window ".NET-Broadcast Event Window 1.0.5 - This program
is not responding" etc. I would guess that this is because I am not calling
Application.Run because I need to run my own loop waiting for my named event.
Any further suggestions gratefully received. (Maybe I need to make it a
Windows application and override WndProc?)

BTW there seem to be a lot of problems with the newsgroups at the moment.
The "read the response" links in the notification emails haven't worked for
weeks, and 9 times out of 10 I get "page does not exist" when I try to access
a newsgroup. Can you pass the message on to MS.
--
Dave
"Willy Denoyette [MVP]" wrote:

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:C1******** *************** ***********@mic rosoft.com...
| Thanks Willy, but if I implement it as a Windows app with a main window,
| execution then disappears into the main window (ie the main window's
message
| loop) so how do I then wait for my named event?
| --
| Dave
|
|
| "Willy Denoyette [MVP]" wrote:
|

Sorry if I wasn't clear, point is that you don't need a main windows (a Form
instance), all you need is a message pump to handle this.
You can start a separate thread to handle your main task before you start
the message loop by calling Application.Run ().

Something like this should do:
[STAThread]
static void Main()
{
SystemEvents.Se ssionEnded += new
SessionEndedEve ntHandler(Sessi onEnd);
// Start a new backgound thread to handle your main task here.
// Start a message pump.
Application.Run ();
}
static void SessionEnd(obje ct s, SessionEndedEve ntArgs e)
{
...
}

Willy.

May 30 '06 #5
Dave <Da**@discussio ns.microsoft.co m> wrote:
I was confused there as your original reply said "you need a main windows".
I have implemented the event (I used SessionEnding rather than SessionEnded)
but it still doesn't work - when I log off the SessionEnding event is never
fired, but I get a window ".NET-Broadcast Event Window 1.0.5 - This program
is not responding" etc. I would guess that this is because I am not calling
Application.Run because I need to run my own loop waiting for my named event.
Any further suggestions gratefully received. (Maybe I need to make it a
Windows application and override WndProc?)


I've tested this application and it works for me:

---8<---
using System;
using System.IO;
using System.Threadin g;
using System.Windows. Forms;
using Microsoft.Win32 ;

class App
{
static void Main()
{
EventWaitHandle closing = new ManualResetEven t(false);
bool running = true;

SystemEvents.Se ssionEnded += delegate
{
running = false;
closing.Set();
File.WriteAllTe xt("\\Log.txt" , "Session ended");
};

Thread worker = new Thread((ThreadS tart)delegate
{
for (;;)
{
WaitHandle.Wait Any(new WaitHandle[] { closing
/* , X, etc. */ });
if (!running)
break;

// Do work because of event X or whatever
}
File.WriteAllTe xt("\\Closed.tx t", "Success!") ;
});
worker.Start();

Application.Run ();
}
}
--->8---

Perhaps you can adapt your application along these lines?

-- Barry

--
http://barrkel.blogspot.com/
May 30 '06 #6
Dave <Da**@discussio ns.microsoft.co m> wrote:
I would guess that this is because I am not calling
Application.Run because I need to run my own loop waiting for my named event.
Any further suggestions gratefully received.


I should point out that each thread is separate as far as message loops
are concerned. You can call Application.Run () on the main thread so that
the session ended event occurs, and create your own message loop (or
call Application.Run () again) on a different thread, without problems.

-- Barry

--
http://barrkel.blogspot.com/
May 30 '06 #7
Are you sure you compiled as a Windows application? Console applications
cannot receive Session ending messages.

Consider following sample to get you started.

public class Program
{
static int keepRunning;
[STAThread]
static void Main()
{
Program prog = new Program();
// Optionally install a tray icon and attached context memu
prog.Initialize Tray();
Interlocked.Exc hange(ref keepRunning, 1);
Thread t = new Thread(new ThreadStart(pro g.ThreadJob));
t.Start();
// Register handler
SystemEvents.Se ssionEnding += new
SessionEndingEv entHandler(prog .SessionEnd);
// Start the message loop, this one creates a parking window and
associated message queue,
// windows messages will be posted to this queue.
Application.Run ();
}
void ThreadJob()
{
// Initialize thread invariants like synchronization handles
// ...
// keep running the loop until requested to terminate
while (Interlocked.Ex change(ref keepRunning, 1) == 1)
{
// this is your task loop, make sure you don't start blocking
operations in this loop, start another thread when needed.
}
// Clean-up thread invariants here
}
void InitializeTray( )
{
// Initialize context menu
MenuItem cntxtMenuItem = new MenuItem();
cntxtMenuItem.I ndex = 0;
cntxtMenuItem.T ext = "E&xit";
cntxtMenuItem.C lick += new System.EventHan dler(this.cntxt Menu_Click);
ContextMenu cntxtMenu = new ContextMenu();
cntxtMenu.MenuI tems.AddRange(
new MenuItem[] {cntxtMenuItem} );
// Attach context menu to notifyIcon
NotifyIcon notifyIcon;
notifyIcon = new NotifyIcon();
notifyIcon.Icon = new System.Drawing. Icon(@"whatever .ico");
notifyIcon.Visi ble = true;
notifyIcon.Text = "My program";
notifyIcon.Cont extMenu = cntxtMenu;
}
void cntxtMenu_Click (object Sender, EventArgs e) {
Interlocked.Exc hange(ref keepRunning, 0); // Ask threads to terminate
Application.Exi t(); // exit application
}

void SessionEnd(obje ct s, SessionEndingEv entArgs e)
{
// signal auxiliary thread(s) to stop
Interlocked.Exc hange(ref keepRunning, 0);
// cleanup program invariants when needed (constrained by session
end time-out)
//...
// and accept session to end
e.Cancel = true;
}
}
}
}

Willy.
PS. Can't help you with your newsreader issue, apparently you aren't using a
NNTP newsreader (and posting host), I suggest you try another posting host
and/or reader.

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:7F******** *************** ***********@mic rosoft.com...
| Hi Willy
| I was confused there as your original reply said "you need a main
windows".
| I have implemented the event (I used SessionEnding rather than
SessionEnded)
| but it still doesn't work - when I log off the SessionEnding event is
never
| fired, but I get a window ".NET-Broadcast Event Window 1.0.5 - This
program
| is not responding" etc. I would guess that this is because I am not
calling
| Application.Run because I need to run my own loop waiting for my named
event.
| Any further suggestions gratefully received. (Maybe I need to make it a
| Windows application and override WndProc?)
|
| BTW there seem to be a lot of problems with the newsgroups at the moment.
| The "read the response" links in the notification emails haven't worked
for
| weeks, and 9 times out of 10 I get "page does not exist" when I try to
access
| a newsgroup. Can you pass the message on to MS.
| --
| Dave
|
|
| "Willy Denoyette [MVP]" wrote:
|
| >
| > "Dave" <Da**@discussio ns.microsoft.co m> wrote in message
| > news:C1******** *************** ***********@mic rosoft.com...
| > | Thanks Willy, but if I implement it as a Windows app with a main
window,
| > | execution then disappears into the main window (ie the main window's
| > message
| > | loop) so how do I then wait for my named event?
| > | --
| > | Dave
| > |
| > |
| > | "Willy Denoyette [MVP]" wrote:
| > |
| >
| > Sorry if I wasn't clear, point is that you don't need a main windows (a
Form
| > instance), all you need is a message pump to handle this.
| > You can start a separate thread to handle your main task before you
start
| > the message loop by calling Application.Run ().
| >
| > Something like this should do:
| >
| >
| > [STAThread]
| > static void Main()
| > {
| > SystemEvents.Se ssionEnded += new
| > SessionEndedEve ntHandler(Sessi onEnd);
| > // Start a new backgound thread to handle your main task here.
| > // Start a message pump.
| > Application.Run ();
| > }
| > static void SessionEnd(obje ct s, SessionEndedEve ntArgs e)
| > {
| > ...
| > }
| >
| > Willy.
| >
| >
| >
May 30 '06 #8
Brilliant. Thanks Barry, that gave me the clue I needed. All works fine now.
--
Dave
"Barry Kelly" wrote:
Dave <Da**@discussio ns.microsoft.co m> wrote:
I was confused there as your original reply said "you need a main windows".
I have implemented the event (I used SessionEnding rather than SessionEnded)
but it still doesn't work - when I log off the SessionEnding event is never
fired, but I get a window ".NET-Broadcast Event Window 1.0.5 - This program
is not responding" etc. I would guess that this is because I am not calling
Application.Run because I need to run my own loop waiting for my named event.
Any further suggestions gratefully received. (Maybe I need to make it a
Windows application and override WndProc?)


I've tested this application and it works for me:

---8<---
using System;
using System.IO;
using System.Threadin g;
using System.Windows. Forms;
using Microsoft.Win32 ;

class App
{
static void Main()
{
EventWaitHandle closing = new ManualResetEven t(false);
bool running = true;

SystemEvents.Se ssionEnded += delegate
{
running = false;
closing.Set();
File.WriteAllTe xt("\\Log.txt" , "Session ended");
};

Thread worker = new Thread((ThreadS tart)delegate
{
for (;;)
{
WaitHandle.Wait Any(new WaitHandle[] { closing
/* , X, etc. */ });
if (!running)
break;

// Do work because of event X or whatever
}
File.WriteAllTe xt("\\Closed.tx t", "Success!") ;
});
worker.Start();

Application.Run ();
}
}
--->8---

Perhaps you can adapt your application along these lines?

-- Barry

--
http://barrkel.blogspot.com/

May 30 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
16249
by: John Lull | last post by:
I'm writing a multithreaded COM server to manage a pool of hardware resources. All objects are designed to be thread-safe, and I've set sys.coinit_flags to COINIT_MULTITHREADED before importing pythoncom. The problem is that all requests to the server seem to be serialized by COM. To demonstrate the problem, I'm including a simple test...
8
2726
by: Ben | last post by:
Hi all, I implemented a stack in C++ in 2 different ways and I'd like to know which approach is better than the other.. and if there is any difference between the two? I'd also like to know if the destructor i'm using is correct.. I got segmentation fault in my second approach while I quit the program. I appreciate any help.... My first...
70
11604
by: Rajan | last post by:
Hi, I am trying to simulate a memcpy like this void* mem_cpy(void* dest, void* src, int bytes) { dest = malloc(bytes); } Now if I want to copy the bytes from src to dest, how do I copy these bytes. I am stuck here.
7
3529
by: Jeroen Ceuppens | last post by:
Hi, When I draw a bitmap on a form, the bitmapdrawing disappears when I move the form, how is it possible to lock the drawing so it stays visible when you move or do somethings else.... Thx Jeroen
10
4002
by: Charles Law | last post by:
For some reason, when I click the X to close my MDI parent form, the action appears to be re-directed to one of the MDI child forms, and the parent remains open. I am then unable to close the application. What should happen, is that the main MDI form should close, taking the child forms with it. There is code to loop through the child forms,...
1
1184
by: kevininstructor | last post by:
I created two classes called "site" and "Sites" which use 'BinaryFormatter' to load and save class information to a disk file. In my test application all works fine but when implementing into another application the code fails with a message indicating there is a missing assembly. The missing assembly is the project which serialized the class...
2
2005
by: ern | last post by:
My command-line application must be able to run text scripts (macros). The scripts have commands, comments, and flags. Comments are ignored (maybe they are any line beginning with " ; ") Commands are executed as if the user *manually* typed them in the console. Flags are special commands that tell the program where to BREAK, LOOP, START. A...
6
2255
by: Dasn | last post by:
Hi, there. 'lines' is a large list of strings each of which is seperated by '\t' I wanna split each string into a list. For speed, using map() instead of 'for' loop. 'map(str.split, lines)' works fine , but... when I was trying: I got "TypeError: 'list' object is not callable".
7
8538
by: koonda | last post by:
Hi all, I posted my message earliar and I got some positive feedbacks but that didn't help me to solve some programming problems. I have an Assignment due 20th of this month, next monday. The Assignment is about creating a Connect Four Game. I have designed the board and two players can play and fill the board. But when one playe fills 4...
0
7888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7811
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8314
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8185
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6571
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5689
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2317
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.