Visual Studio C++ How to get the Form not freezing while calling a time-consuming function? - visual-studio-2010

I am making a C++/CLI Forms application.
In the main window of my app I have a button. When I click that button I call the Load function. Below there is the C++/CLI code:
private: System::Void Button1_Click(System::Object^ sender, System::EventArgs^ e) {
Load();
}
The function Load() is a time-consuming function. It uses the cURL library to send several HTTP GET request to a website.
In the Form I also included a ProgressBar and a textLabel showing the current request being sended.
The problem is that when I click the button and call the function the Form just freezes. I can't see the progressBar and Textlabel changing it's value while the function Load() is called, the Form is just freezed. When the function Load() has finished sending request, suddenly the progressBar change It's value to 100%.
I hope I described my problem clearly enough to understand it.

Move your task to another thread, or call Application.DoEvents();, just after you updating your scrollbar value.

Either break the task into smaller parts (design a finite state machine or use continuations) or use a separate thread.
The first approach takes more getting used to, but it's easier for an experienced programmer to get right. Threading requires synchronization which is very detail-oriented and causes a lot of hidden sporadic bugs which are extremely difficult to debug.

Call Form1.Refresh() every time you update an element of the form (say Form1). It will show the results immediately.

Before any line command that make probably any load time ...Write This:
System::Windows::Forms::Application::DoEvents();

Related

GtkButton label updates

I am designing a GUI using C, Glade, and Gtk.
I have some signals configured in glade to update the labels of various widgets, mainly GtkButton and GtkLabel. The overall functionality is that when a certain radio button is clicked, all button and labels change in response (language selection).
I am using the function gtk_label_set_label(...) in the widgets _draw() function and it works as expected (text changes, g_print occurs (once)).
gboolean on_lblMyLabel_draw(GtkLabel *label, gpointer *user_data) {
gtk_label_set_label(label, "custom text");
g_print("%s\n", "custom text");
return FALSE;
}
However, when I attempt the same from a button,
gboolean on_btnMyButton_draw(GtkButton *button, gpointer *user_data) {
gtk_button_set_label(button, "custom text");
g_print("%s\n", "custom text");
return FALSE;
}
The text does not update, but dissappears, and the g_print() statement prints forever (as if the draw is recursively calling itself).
Funnily, if I move the button code from _draw to _click, it works as expected, however, I need the GUI to redraw itself, so updating on click is impractical.
Is there a way, using _draw() to prevent this?
Is there a better way to do this?
thx!
Is there a way, using _draw() to prevent this?
No, and you shouldn’t be using the draw signal for this either. It has an entirely different purpose, and will be called each time a widgets redraws itself. That’s also the reason why your button is going into an infinite recursion: you changed its label so it figures it needs to be redrawn; that redraw leads to your callback being called, which again changes the label, etc etc
Is there a better way to do this?
Yes, and you mention it yourself already: make sure you do the logic of changing the widgets in the appropriate place (for example, on a click event), and let the GTK widgets take care of redrawing themselves.
Unless you’re doing something very exotic (like not running an event loop, which you automatically get with GtkApplication), this will all work fine.

wxWidgets event focus textcontrol

I have another wxWidgets question regarding events and focus.
I have already looked at the tutorials and this old question here but I am still running into problems C++ Event (Focus) Handling
Basically I have a dialog with two wxTextCtrl elements and a Button.
What I would like to achieve is, that when I click on button it needs to tell me which of the two elements previously had the focus.
In the constructor of my Dialog I created all the elements and then connected them to the eventhandler like this: Ttop->Connect(TOP,wxEVT_KILL_FOCUS,(wxObjectEventFunction)&UI_ADDENTRY::hasfocus);
Tbottom->Connect(BOTTOM,wxEVT_KILL_FOCUS,(wxObjectEventFunction)&UI_ADDENTRY::hasfocus);
then there is the eventhandler that safes the id into focus
void UI_ADDENTRY::hasfocus(wxFocusEvent& event){
focus= event.GetId();
event.Skip();}
however when i try to access focus in the Button function it always tells me: 0 instead of TOP or BOTTOM / the ids that I gave the textcontrols
void UI_ADDENTRY::OnRecord(wxCommandEvent &event){
wxString tmp;
tmp << this->focus;
wxMessageBox(tmp);}
What am I doing wrong? is there another way of finding out which of the two textbox has been in focus last?
Thank you
The most fool proof way is to catch EVT_SET_FOCUS in your text controls and remember the last one that received it. This is not more difficult than what you are doing but should work without problems.
FWIW EVT_KILL_FOCUS can't, unfortunately, be consistently implemented on all platforms, in particular GTK+ doesn't give any information about the window focus is being lost to.
In think u mean event.GetWindow().GetId(). Though I'm not sure how ur casting from int to string.

How modal dialog is implemented?

For a long time I have been wondering how modal dialog is implemented.
Let me take Qt as an example. (Nearly all GUI toolkit has this mechanism)
In the main event loop, a slot is called, and in this slot a modal dialog is opened. Before the dialog is closed, the slot doesn't return control to the main event loop. So I thought that the main event loop is blocked and become unresponsive. Apparently this is not true, since when you open a modal dialog, the background main window is still working, like repainting its UI or keep displaying a curve or some graph. It just becomes not to accept any user input.
I did an experiment. I didn't open a modal dialog in the slot, but start a new thread there, and wait for the thread to finish in that slot. This definitely blocked the main event loop.
How modal dialog is implemented after all? How does it keep main event loop unblocked but at the same time blocked the calling slot?
There is only ever a need for a single event loop, and it does not block when a modal dialog appears. Though, I suppose, different toolkits may handle this differently. You would need to consult the documentation to know for sure. Conceptually, however, it all works in the same way.
Every event has a source where the event occured. When a modal dialog appears, the event loop either ignores or redirects all events that originate outside of the dialog. There's really no magic to it. Generally speaking, it's like an if statement in the event loop code that says "if (modal_is_shown() and !event_is_in_modal_window()) {ignore_and_wait_for_next_event()}". Of course, the logic is a bit more complicated, but that's the gist of it.
If you're looking for examples here's another one:
In Tk, there is only ever one event loop. Modal behavior (doesn't have to be dialog, can also be tooltips, textbox etc) is simply implemented by making the main window ignore mouse and keyboard events. All other events like redraws etc. can still be serviced because the event loop is still running.
Tk implements this via the [grab] function. Calling grab on a UI object makes it the only object able to respond to keyboard and mouse events. Essentially blocking all other objects. This doesn't mess with the event loop. It merely temporarily disables event handlers until the grab is released.
It should be noted that Unix-like operating systems running X also has grab built in to the windowing system. So it's not necessarily implemented merely by UI toolkit libraries but is sometimes also a built in feature of the OS. Again, this is implemented by simple blocking/disabling of events instead of instantiating separate event loops. I believe this also used to be the case for the older MacOS before OSX. Not sure about OSX or Windows though. Even though modality is often implemented by the OS itself, toolkits like Qt and Tk often implement their own mechanisms to standardize behaviors across different platforms.
So the conclusion is, it is not necessary to block the main event loop to implement modality. You just need to block the events and/or event handlers.
The answer by https://stackoverflow.com/users/893/greg-hewgill is correct.
However, reading the follow-up discussion between him and https://stackoverflow.com/users/188326/solotim , I feel that there is room for further clarification, by means of prose and some pseudo-code.
I'll handle the prose part with a fact-list:
The main message loop does not run until the modal activity is finished
However, events are still delivered while the modal activity is running
This is because there is a nested event loop within the modal activity.
So far I just repeated Greg's answer, please bear with me as it is for continuity's sake. Below is where I hope to contribute additional, useful info.
The nested event loop is part of the GUI toolkit, and as such, it knows the callback functions related to every window in existence
When the nested event loop raises an event (such as a repaint event directed to the main window), it invokes the callback function associated with that event. Note that "callback" here may refer to a method of a class representing a window, in object-oriented systems.
the callback function does what is needed (e.g., repaint), and returns right back to the nested message loop (the one within the modal activity)
Last, but not least, here's pseudo-code to hopefully illustrate further, using a fictitious "GuiToolkit":
void GuiToolkit::RunModal( ModalWindow *m )
{
// main event loop
while( !GuiToolkit::IsFinished() && m->IsOpen() )
{
GuiToolkit::ProcessEvent(); // this will call
// MainWindow::OnRepaint
// as needed, via the virtual
// method of the base class
// NonModalWindow::OnRepaint
}
}
class AboutDialog: public ModalWindow
{
}
class MainWindow: public NonModalWindow
{
virtual void OnRepaint()
{
...
}
virtual void OnAboutBox()
{
AboutDialog about;
GuiToolkit::RunModal(&about); // blocks here!!
}
}
main()
{
MainWindow window;
GuiToolkit::Register( &window ) // GuiToolkit knows how to
// invoke methods of window
// main event loop
while( !GuiToolkit::IsFinished() )
{
GuiToolkit::ProcessEvent(); // this will call
// MainWindow::OnAboutBox
// at some point
}
}
In general, a modal dialog box of this type is implemented by running its own message loop instead of your application's message loop. Messages directed to your main window (such as timer or paint messages) will still get delivered, even during the modal operation.
In some situations, you may have to be careful that you don't recursively do the same thing repeatedly. For example, if you trigger a modal dialog box on a timer message combined with some persistent flag, you'll want to make sure you don't keep bringing up the same dialog box repeatedly whenever the timer message fires.

Delphi TForm OnCreate gets called multiple times

I hope I can explain this problem decently well!
I'm trying to implement a ReWire audio device as a Delphi .dll. If you don't know what ReWire is, don't worry about it. What's important is that my code compiles into a .dll, and I get calls from the ReWire system into my .dll to open up a display, check if the display is opened, and close it again.
When I get the call to launch, I do the following:
if not Assigned(form) then
form := TMyForm.Create(nil);
form.Show;
where form is a global variable inside of my Delphi library (maybe a problem?). I have hooked up MyForm's OnCreate event to do some interesting things like prepare an array of stuff I want to work with.
So far everything's good. My form has a little button in it that opens up a TOpenDialog. I find that as soon as that dialog closes, somehow the OnCreate event is firing again in my form!
I have checked that OnDestroy is not being called, so I have no idea why OnCreate is getting called again.
Unfortunately I'm not really sure what information is relevant, but here's the call stack the first time around (when the form is first set up):
As expected, ReWire is making a call into my .dll to Launch the Panel application, so I create my form. Great, things are looking good.
Then inside my form, I open up a little dialog, select a file, and do some operations. Out of left field, OnCreate is called again, and here's the call stack that time:
It's a crazy party of calls! Reaper (at the bottom) is the ReWire host I'm using to test my application, but I have no idea what's going on inside that stack trace because none of it is my code. Suddenly the event just gets called when I don't think it should, because OnDestroy wasn't even called.
The only other important thing I can think of is that if I print out the address of the Sender, it's different each time, so it's somehow getting Created again or something, but I've checked that I only call the MyForm.Create once.
Any ideas as to how this type of thing could happen?
In the first stack trace, the OnCreate call is preceded by a call to TCustomForm.Create(), which is correct behavior. In the second stack trace, the OnCreate call is preceded by a call to TObject.Create() instead, which is not correct behavior. That leads me to think that something in your button OnClick event handler is either constructing an object with a bad VMT, or is otherwise corrupting memory in general and causing a bad jump into code that just happens to be occupied by your TForm class. Either way, double check your OnClick logic for bugs.
Check on (any)where you are setting the form variable to nil. It may be that it's being set to nil without freeing the form it's pointing to, and so next time your launch code is called it's creating another instance of the form.

Intercepting and Disabling Global Mouse Events

I have a problem with my mouse. Every now and then it will double click when I only single click. I know this is a problem with the mouse, and I've contacted the manufacturer, still waiting for a reply. But in the meantime I was wondering if there was a way that I could find out when the left mouse button had been clicked twice within a very short period (probably 1-10 milliseconds) of time, and disable the second click.
I mostly know how to use hooks, so that's not the problem, my main question is how to stop an event from happening, if that's possible.
The information on how to prevent the mouse message from being processed is in the documentation of the "LowLevelMouseProc callback function" in MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986(v=vs.85).aspx
Specifically, it says: "If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure." So, if you know about windows hooks, you know how to do it.
EDIT: Actually, now that I think more about it, you don't want to discard any event. You simply want to transform the doubleclick event into just another left-button-down event. I believe you can do it from within the hook handler, and it will work. Have you tried it?
In C#'s WinForms, you write an event handler involving the mouse receiving a MouseEventArgs object. Inside it, you can access certain info such as the number of times it was clicked, for example.
protected void RowClicked(object sender, MouseEventArgs evt)
{
// Trigger it when the mouse was clicked only once
if( evt.Button.Clicks == 1 ) {
// ... more things ...
}
return;
}
Other GUI libraries have other possibilities. That said, your problem has nothing to do with GUI libraries. You have to change the sensitivity of your mouse, in the configuration options of your operating system. For example, in the Windows' control panel, you can change how much time has to pass between a click and another one to be considered a doble-click. In lUbuntu, you can do the very same, in System menu >> Preferences >> Keyboard and Mouse.

Resources