wxwidgets's mainloop() and boost::thread - boost

In short I'm trying to implement a GUI to my networking app. Both of them have mainloop() so I'm trying to put them into separate threads and I'm using boost::thread for it.
//standard initialization of boost::thread
GuiThread.join();
NetworkThread.join();
However, above crashes for some reason unknown. I'm searching for any way to do the same thing so any suggestion will be appreciated.
Thanks in advance, Red.
EDIT:
I'm creating boost::thread GuiThread of the wxWidgets mainloop like so:
boost::thread GuiThread = boost::thread ( boost::bind( &myAppClass::MainLoop(), this));
and Networkthread same way.
then i rewrite wxApp OnRun() function like so:
int OnRun() {
GuiThread.join();
NetworkThread.join();
return 0;
}
when i run it ( in vs2010 ), it says: myApp.exe has triggered a breakpoint and if i press continue it stops showing the window, if i press break it shows me assembly.

You must run wxWidgets main loop from the same thread that initialized the library. If you want to run it in a thread other than main, it means that you can't use the standard IMPLEMENT_APP() macro but must do the initialization yourself, e.g. by calling wxEntry() manually.

Related

QProcess fails to execute external executable

I am struggling to find a solution to my problem, but I simply have no clue how to solve it.
I am creating an user-interface for some programs I made (so you can through simply pressing a button start an executable).
So I thought of using qt.
So I read a lot about the QProcess and tried to use it.
At the first executable of mine I tried to start it through QProcess::start(), but it didn't work so I tried it with QProcess:execute():
QProcess *proc = new QProcess(this);
QDir::setCurrent("C:\\DIRTOTHEEXE\\");
QString program="HELLO.exe";
proc->execute(program);
This executes my program perfectly and works nice.
So I tried to do the same with my other exe, but it didn't work
QProcess *myproc = new QProcess(this);
QDir::setCurrent("C:\\DIRTOTHEEXE\\");
QString program="HelloWorld.exe";
myproc->start(program);
The called executable simply prints "Hello World" and returns 0 then.
So now my question is: What could cause this behaviour and why can't I use QProcess::start() for the first executable?
Btw: I also tried to set the workingDirectory() to the path of the exe, but also that didn't work.
Hope someone can help me.
EDIT:
So the program is executed but crashes right after printing out one line.
EDIT: Here the HelloWorld source.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout<<"HELLO WORLD!!"<<endl;
return 0;
}
QProcess has 3 functions for starting external processes, such as: -
start
execute
startDetached
The latter two, execute and startDetached are static, so don't need an instance of QProcess to call them.
If you use start, you should at least be calling waitForStarted() to let the process setup properly. The execute() function will wait for the process to finish, so calling waitForStarted is not required.
As you've only posted a small amount of code, we can't see exactly what you're trying to do afterwards. Is that code in a function that ends, or are you trying to retrieve the output of the process? If so, you definitely should be calling waitForStarted if using start().
If you only want to run the process without waiting for it to finish and your program is not bothered about interacting with the process, then use startDetached: -
QProcess::startDetached("C:\\DIRTOTHEEXE\\HELLO.exe");

SetWindowsHook Global not very Global

I'm playing around with SetWindowsHookEx, specifically I would like be able to find out about any window (on my desktop) thats been activated, via mouse or keyboard.
Reading through MSDN docs for SetWindowsHookEx it would appear that a WH_CBT type would do the job. I've created a dll and put all the code in there, which I control from a gui app (which also handles the unhook).
BUT I only appear to be getting the activation code when I activate my gui app though, any other app I activate is ignored.
In my dll I have the setup code and the CBTProc like so:
LRESULT WINAPI CBTProc(int Code, WPARAM W, LPARAM L) {
if(Code<0) CallN....
if (Code == HCBT_ACTIVATE) { // never get unless I activate my app
HWND a = reinterpret_cast<HWND>(W);
TRACE("this window was activated %d\n", a);
}
CallNext....
}
EXPORTED HHOOK WINAPI Setup(HWND MyWind) {
...
// gDllUInstance set in dllmain
return SetWindowsHookEx(WH_CBT, CBTProc, gDllUInstance, 0);
}
All pretty simple stuff, i've tried moving the setup out of the dll but I still get the same effect.
It would appear that the dll is getting loaded into other processes, I'm counting the number of DLL_PROCESS_ATTACHs I'm getting and can see its going up (not very scientific i know.
NOTE that this is 32 bit code running on 32bit OS - win2k3.
Are my expectations of the hooking mechanism wrong? should I only be getting the activation of my app or do I need a different type of hook?
EDIT: the trace function writes to a file telling me whats sending me activations
TIA.
Turns out its working ok, as Hans points out, i'm just not seeing the output from the debugger from the other processes, if I put in some extra tracing code - one trace file per attached process - I can see can see that things are working after all.
Many thanks for the replies.

Dialog box to abort a while-loop in C++/CLI

I have a while loop executed in a function. While the loop is executed, I would like to have a dialog box with an "Abort" button to show up on the screen on Windows. If I press the Abort button, the program would terminate the while loop. It's like a dialog which pops up when a file is copied. Could anybody suggest a simple way to do this with C++/CLI or something similar?
Since I don't have a lot of experience with C++/CLI, I would appreciate if you could provide me with code snippets or sample codes.
Using a separate thread is the modern way to do this, but there is another approach.
You can take the guts of your while loop and put them in an event handler. Arrange to have the message loop call this event handler again and again until the job it done (e.g., with a timer or idle processing). In the mean time, you can display a non-modal pop-up dialog. This is how printing used to work in the pre-emptive multitasking era. See SetAbortProc.
I'd recommend that second thread approach listed by others. I just wanted to point out that it's not the only way.
The construction of the while loop is the easy part. What makes it hard is you'll have to put the abort dialog in a different thread and then coordinate a flag in the while condition with the dialog. This is usually handled with semaphores which are known to be difficult to code without subtle side-effects.
The while loop, at a minimum, will need to have a mechanism that allows the event queue to get processed AND periodically checks for a change in the status of the abort semaphore.
//psuedo-code below
bool f_abort = false;
while (!f_abort)
{
do_partial_work();
f_abort = checkForAbort();
sleep(0); // don't want to lock the CPU
}
I'm not an expert in threads so I'll have to point you to other resources for what to do in checkForAbort().
Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay
Win32 synchronization
Is putting thread on hold optimal?
Thread for Windows form
One simple (but poor) example could be this one:
#include "stdafx.h"
#include "windows.h"
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Threading;
DialogResult *res=new DialogResult(DialogResult::No);
void waitForUserAction()
{
while(*res==DialogResult::No)
{
*res=System::Windows::Forms::MessageBox::Show("Exit the loop ? YES/NO","TEST",
MessageBoxButtons::YesNo,MessageBoxIcon::Question);
if(*res==DialogResult::Yes)
Console::WriteLine(L"Exit by user");
}
}
int main()
{
ThreadStart ^start=gcnew ThreadStart(waitForUserAction);
Thread ^pThread=gcnew Thread(start);
int a=0;
pThread->Start();
while(*res!=DialogResult::Yes)
{
a=a+1;
Console::WriteLine(L"Loop processing here...{0}",a);
}
//pThread->Abort();
return 0;
}
You can check this article for more info on the topic...

How can I detect if "Press any key to continue . . ." will be displayed?

When running a console application in Visual Studio, depending on your settings, it will add a prompt after the program exits:
Press any key to continue . . .
I have found how to detect if I am running under the debugger(use Debugger.IsAttached), but it isn't helpful. Press CTRL-F5 to Start Without Debugging sets this flag to false, yet still shows the prompt.
I want to detect this because I'd like to display my own message and wait for a keypress, but not double up keypress checks.
I don't want to muck with my general Visual Studio settings. If I can disable it for this project in a way that can be checked into source control, that would also work.
What mechanism is used to append this prompt, and how do I detect it?
Or how do I disable it per-project, and check this change into source control?
Add the following code to the console application:
public static class Extensions {
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern bool TerminateThread(IntPtr hThread, uint dwExitCode);
public static Process GetParentProcess(this Process x) {
return (
from it in (new ManagementObjectSearcher("root\\CIMV2", "select * from Win32_Process")).Get().Cast<ManagementObject>()
where (uint)it["ProcessId"]==x.Id
select Process.GetProcessById((int)(uint)it["ParentProcessId"])
).First();
}
public static IEnumerable<Process> GetChildProcesses(this Process x) {
return (
from it in (new ManagementObjectSearcher("root\\CIMV2", "select * from Win32_Process")).Get().Cast<ManagementObject>()
where (uint)it["ParentProcessId"]==x.Id
select Process.GetProcessById((int)(uint)it["ProcessId"])
);
}
public static void Abort(this ProcessThread x) {
TerminateThread(OpenThread(1, false, (uint)x.Id), 1);
}
}
And then modify your code like this:
class Program {
static void Main(String[] args) {
// ... (your code might goes here)
try {
Process.GetCurrentProcess().GetParentProcess().Threads.Cast<ProcessThread>().Single().Abort();
}
catch(InvalidOperationException) {
}
Console.Write("Press ONLY key to continue . . . ");
Console.ReadKey(true);
}
}
So, everything we are expecting is done now. I consider this as a workaround solution. It works under Windows XP SP3 and I guess that it would work with newer Windows operating systems. Under Visual Studio, applications are always a spawned process. In older Visual C++ 6.0, it spawned by the IDE by calling VCSPAWN.EXE; in Visual Studio 2010, your application runs with following command line when Start Without Debugging:
"%comspec%" /c ""your application filename" & pause"
So it is impossible to reach the goal in fully managed ways; because it was NOT under the application domain.
Here we use the managed way of WMI to enumerate the processes, and encapsulate the unmanaged WINAPIs to terminate the ProcessThreads, because the ProcessThread is not supposed to be normally aborted; it's provided like something for read-only.
As mentioned above, the application was spawned with the particular command line; it would have a single thread creates a single process signature, so we used the Single() method to retrieve that thread and terminate it.
When we start the application under an existing command prompt, it is just the same scenario of Start Without Debugging. Moreover, when Start Debugging, the application process is created by devenv.exe. It has a lot of threads, we known that and won't abort any thread, just prompt and wait for a key press. This situation is similar to starting application with double-clicking or from context menu. This way, the application process is created by the system shell, usually Explorer.exe and it also has a lots of threads.
In fact, if we can successfully abort the thread it implies that we have the permissions to kill the parent process. But we do NOT need to. We just need to abort the only thread, the process terminates automatically by system when it has no more threads. Killing the parent process by identifying that the calling process is %comspec%, is another way to do the same thing, but it's a dangerous procedure. Because the process spawning the application might have other threads which have any number of threads create a process matches %comspec%. You may kill a critical work of process with carelessness or just growing the complexity of checking whether the process is safe to kill. So I consider a single thread creates a single process as a signature of our parent process which is safe to kill/abort.
WMI is modern, some of WINAPIs might become deprecated in the future. But the real reason of this composition is for its simplicity. The old Tool Help Library is such complicated like the ways to convert ProcessThread to System.Threading.Thread. With LINQ and extension methods, we can make the code simpler and more semantical.
Sounds like this prompt is provided by the pause command. This command is automatically added by Visual Studio.
When you run your project outside of Visual Studio, there is no reason to "detect" this command. You can safely assume that it will not be added to your program. This means you can go ahead and add whatever prompt you want, similar to:
Console.WriteLine("Press any key...");
Console.Read();
See this question.
Here is a piece of code that should do it:
class Program
{
static void Main(string[] args)
{
// do your stuff
if (!WasStartedWithPause())
{
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
public static bool WasStartedWithPause()
{
// Here, I reuse my answer at http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way
Process parentProcess = ParentProcessUtilities.GetParentProcess();
// are we started by cmd.exe ?
if (string.Compare(parentProcess.MainModule.ModuleName, "cmd.exe", StringComparison.OrdinalIgnoreCase) != 0)
return false;
// get cmd.exe command line
string cmdLine = GetProcessCommandLine(parentProcess);
// was it started with a pause?
return cmdLine != null & cmdLine.EndsWith("& pause\"");
}
public static string GetProcessCommandLine(Process process)
{
if (process == null)
throw new ArgumentNullException("process");
// use WMI to query command line
ManagementObjectCollection moc = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId=" + process.Id).Get();
foreach (ManagementObject mo in moc)
{
return (string)mo.Properties["CommandLine"].Value;
}
return null;
}
That message has nothing to do with your program. You can add to your program anything you like and it will perform in the same way as it would, if you were to run it from the command prompt.
Visual studio displays it for the purpose of showing you that its execution has finished running, so you know it ended correctly. If you wish to skip it you could try to "run without debugging" (or something like that; it's just below "run with debugger").
This is the output of "pause" command which is added by visual studio. If you see this, the program is ended. Which comes to a question like is it possible for an application to detect that it self is ended. I think this is not logical.
Won't help to detect, but will add the same prompt when you run with debugger attached (F5) if you add this to the end of Main:
if (Debugger.IsAttached)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
It will in practice do the same as Ctrl + F5 does with & pause
This prompt is given when the command
system("pause")
is used.
Even I faced this problem. You can either use the function _getch() under conio.h for waiting for key press.
So you can use the following code:
cout<<"your message here"
_getch()
This would wait for the key press and display your own prompt.

win32 threads in Qt

Is there a way to create a thread in Qt without using subclassing (ie. making a QThread class)? It's getting difficult sending data into the thread. Is is possible to use win32 threads in Qt if so can someone give me an example on how to?
Thanks.
You shouldn't necessarily subclass QThread - See discussion here http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
Or if you have many simple tasks and want to have them processed in threaded fashion. QRunnable and QThreadPool provide a quick and easy approach without dealing with threads themselves.
If you just want to run a function in another thread you should check the QT Concurrent Namespace.
The following example will run the function 'aFunction()' in separate thread and will not block on the line where calling the function. Of course there are mechanisms to understand when a function ends, to get a result, to wait for it.
void aFunction(int arg1, double arg2, const QString &string);
int integer = ...;
double floatingPoint = ...;
QString string = ...;
QtConcurrent::run(aFunction, integer, floatingPoint, string);

Resources