Suspending(), Resuming(), Closed() and Uninitialize() are not being called in IFrameworkView - winapi

I've written a simple DirectX11.2 app, which works. I wanted to add some cleanup code for when the app exits, however I noticed that my window does not actually handle closing, suspending, resuming or uninitializing properly.
According to the IFrameworkView documentation, Uninitialize() should get called before the application exits, but it never gets called (https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.core.iframeworkview?view=winrt-19041)
I subscribe to the events that are supposed to fire when a window suspends, resumes, or closes, however it seems like none of those events ever actually fire.
I am under the impression that minimizing the window should suspend the application, clicking on the window from the task bar after it has been minimized should resume the application, and pressing the red X button in the top right corner of the window should close the application, am I wrong?
Here is the relevant code:
// the class definition for the core "framework" of our app
ref class App sealed: public IFrameworkView
{
bool m_windowClosed;
CGame m_game;
public:
// this function subscribes to suspend and resume events, and gets called properly
virtual void Initialize(CoreApplicationView^ appView) {
// set the OnActivated function to handle to Acivated "event"
appView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &App::Suspending);
CoreApplication::Resuming += ref new EventHandler<Object^>(this, &App::Resuming);
m_windowClosed = false;
}
// this function subscribes to the close() event. This function is called properly, but the Closed event never fires
virtual void SetWindow(CoreWindow^ window){
window->Closed += ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::Closed);
}
virtual void Load(String^ entryPoint) {}
virtual void Run() {
m_game.Initialize();
CoreWindow^ Window = CoreWindow::GetForCurrentThread();
// repeat until window closes
while (!m_windowClosed) {
// run processEvents() to dispatch events
// ProcessAllIfPresent makes ProcessEvents return once all events have been processed
Window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
// run the rest of the game code here
m_game.Update();
m_game.Render();
}
// we never get here!
m_game.Finalize();
}
// never called, even though it should ALWAYS be called when the application exits?
virtual void Uninitialize() {
Log("Uninitialize()");
}
void OnActivated(CoreApplicationView^ coreAppView, IActivatedEventArgs^ args) {
CoreWindow^ window = CoreWindow::GetForCurrentThread();
window->Activate();
}
// never called
void Suspending(Object^ sender, SuspendingEventArgs^ args) {
Log("Suspending()");
}
// never called
void Resuming(Object^ sender, Object^ args) {
Log("Resuming()");
}
// never called
void Closed(CoreWindow^ sender, CoreWindowEventArgs^ args) {
m_windowClosed = true;
Log("Close()");
}
};
// the class definition that creates an instance of our core framework class
ref class AppSource sealed : IFrameworkViewSource {
public:
virtual IFrameworkView^ CreateView() {
// create an App class and return it
return ref new App();
}
};
[MTAThread] // define main() as a multi-threaded-apartment function
// the starting point of all programs
int main(Array<String^>^ args) {
// create and run a new AppSource class
CoreApplication::Run(ref new AppSource());
return 0;
}

Upon further research, I notice that Suspend and Resume are generally called when Windows itself suspends (sleep, hibernate) and resumes ("wakes up" from sleep or hibernate).
I have now found that the only event that's called before my app terminates is the CoreWindow::VisibilityChanged event.

Related

VSTO How to hide FormRegion in Reply email [in InlineResponse also]?

So, as the subject says...what is the easiest way to hide FormRegion if email is in Reply mode whether its in a new window or with InlineResponse?
Just set the FormRegion.Visible property which returns a Boolean value that indicates whether the form region is visible or hidden.
Went back to test the approach in my answer after the question from #EugeneAstafiev and -- of course -- this was more complicated than I first thought... but I did get it working with some additional code.
The issue is that when the user clicks "Reply", it opens a new inspector window with a new instance of the FormRegion. So setting the Visible property to false in the event handler sets it only on the current "Read" mode inspector window -- rather than the new "Compose" mode inspector window that gets opened. So, instead the code samples below set up a bool flag property in ThisAddIn called LoadFormRegion that can be toggled to "false" when the Reply or ReplyAll event is fired.
Also, I noticed that setting Visible to false on the FormRegion still draws the area of the FormRegion on the inspector window, just with nothing in it. To completely prevent the FormRegion from loading, you can test for "Compose" mode and then the ThisAddin.LoadFormRegion flag in the FormRegionInitializing event handler located inside of the "Form Region Factory" at the top of the code page -- which is usually folded away from view. In that code block, setting "e.Cancel = true" will prevent the FormRegion from loading at all.
Here is the revised code for the FormRegion, which now subscribes to all three email button click events (Reply, ReplyAll, Forward), and sets the ThisAddIn.LoadFormRegion flag accordingly:
namespace TESTINGOutlookAddInVSTO
{
partial class FormRegion1
{
#region Form Region Factory
[Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
[Microsoft.Office.Tools.Outlook.FormRegionName("TESTINGOutlookAddInVSTO.FormRegion1")]
public partial class FormRegion1Factory
{
// Occurs before the form region is initialized.
// To prevent the form region from appearing, set e.Cancel to true.
// Use e.OutlookItem to get a reference to the current Outlook item.
private void FormRegion1Factory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
{
if (e.FormRegionMode == Outlook.OlFormRegionMode.olFormRegionCompose)
{
var myAddIn = Globals.ThisAddIn;
if (myAddIn.LoadFormRegion == false)
{
e.Cancel = true;
}
}
}
}
#endregion
// Occurs before the form region is displayed.
// Use this.OutlookItem to get a reference to the current Outlook item.
// Use this.OutlookFormRegion to get a reference to the form region.
private void FormRegion1_FormRegionShowing(object sender, System.EventArgs e)
{
// Reset ThisAddIn.LoadFormRegion flag to true (in case user starts
// composing email from scratch without clicking Reply, ReplyAll or Forward)
var myAddin = Globals.ThisAddIn;
myAddin.LoadFormRegion = true;
var myMailItem = this.OutlookItem as Outlook.MailItem;
// Track these events to set the ThisAddIn.FormRegionShowing flag
((Outlook.ItemEvents_10_Event)myMailItem).Reply += myMailItem_Reply;
((Outlook.ItemEvents_10_Event)myMailItem).ReplyAll += myMailItem_ReplyAll;
((Outlook.ItemEvents_10_Event)myMailItem).Forward += myMailItem_Forward;
}
// Sets FormRegionShowing flag on ThisAddin
private void SetFormRegionShowing(bool show)
{
var myAddIn = Globals.ThisAddIn;
myAddIn.LoadFormRegion = show;
}
private void myMailItem_Forward(object Forward, ref bool Cancel)
{
SetFormRegionShowing(true);
}
private void myMailItem_ReplyAll(object Response, ref bool Cancel)
{
SetFormRegionShowing(false);
}
private void myMailItem_Reply(object Response, ref bool Cancel)
{
SetFormRegionShowing(false);
}
// Occurs when the form region is closed.
// Use this.OutlookItem to get a reference to the current Outlook item.
// Use this.OutlookFormRegion to get a reference to the form region.
private void FormRegion1_FormRegionClosed(object sender, System.EventArgs e)
{
}
}
}
And here's the new code for ThisAddIn to setup the LoadFormRegion property flag:
namespace TESTINGOutlookAddInVSTO
{
public partial class ThisAddIn
{
private bool loadFormRegion;
public bool LoadFormRegion { get => loadFormRegion; set => loadFormRegion = value; }
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
LoadFormRegion = true;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
Tested the above and works nearly perfectly... I noticed that if there is a "Draft" reply in the user's Inbox created before the add-in was loaded, clicking on that email to continue editing in the Preview window or a new inspector window will cause some wonky display issues with the FormRegion. However, once I closed out that draft, then everything seemed to return to normal.

Reactive Extensions subscribing to an observable (subject)

I'm just playing around with Reactive Extensions for the first time in a winforms application. Mind you I have been doing web development for the past 4 years, and I am very familiar with observables and observable pattern in knockout, which I am guessing is contributing to my confusion here.
Anyhow, to the question and code. I have a simple winforms experiment (see below) that I was building to illustrate my question. The subscribe below doesn't run until well after the thread in start new is finished. I can trace it the calls to OnNext, but the subscribe doesn't fire at all until sometimes 20-30 seconds later. Can somebody explain this behavior to me?
public partial class Form1 : Form
{
private Subject<int> progress;
private CancellationToken cancellationToken;
private IScheduler _scheduler;
public Form1()
{
InitializeComponent();
CancellationTokenSource source = new CancellationTokenSource();
cancellationToken = source.Token;
_scheduler = new SynchronizationContextScheduler(SynchronizationContext.Current);
}
private void Start_Click(object sender, EventArgs e)
{
progress
.ObserveOn(_scheduler)
//.Throttle(TimeSpan.FromSeconds(5))
.Subscribe(
(i) => {
progressBar1.Do<ProgressBar>(ctl =>
{
ctl.Value = i;
});
},
(ex) => { },
cancellationToken
);
Task counterTask = Task.Factory.StartNew(() =>
{
for (var i = 1; i < 101; i++)
{
Thread.Sleep(500);
progress.OnNext(i);
}
}, cancellationToken,
TaskCreationOptions.LongRunning,
TaskScheduler.FromCurrentSynchronizationContext()
);
}
private void Form1_Load(object sender, EventArgs e)
{
progress = new Subject<int>();
}
}
public static class ControlExtensions
{
public static void Do<TControl>(this TControl control, Action<TControl> action)
where TControl : Control
{
if (control.InvokeRequired)
control.Invoke(action, control);
else
action(control);
}
}
Your issue comes from the fact that your task is running on the UI thread, because you're using TaskScheduler.FromCurrentSynchronizationContext().
Hence your various Sleep calls are blocking the UI thread, freezing the UI (e.g. can't drag the window) and preventing your observable subscription to execute (because the ObserveOn, it's supposed to execute on the UI thread scheduler).
Replace TaskScheduler.FromCurrentSynchronizationContext() by TaskScheduler.Default (background TaskPool threads), and everything will work as you expected.
Note that your call to Do/Invoke is unnecessary, because you're already on the UI thread by the scheduler you've provided.

app_message_outbox_send is not in app space

I am working on a Pebble watch face and I ran into a problem, the function app_message_outbox_send seems to throw an error (which then crashes my app). The error is "[INFO ] E call_internal.c:36 syscall failure! 0..0x8 is not in app space."
The relevant code:
static void askPhoneForCharge(){
if(bluetooth_connection_service_peek()){
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
dict_write_uint8(iter, KEY_PHONE_ASK, 0);
app_message_outbox_send();
}else{
phoneCharging = 0;
phoneCharge = 0;
updatePhoneBattery();
}
}
Here is how I set up the handlers and open the channel:
app_message_register_inbox_received(inboxReceivedCallback);
app_message_register_inbox_dropped(inboxDroppedCallback);
app_message_register_outbox_failed(outboxFailedCallback);
app_message_register_outbox_sent(outboxSentCallback);
app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum());
As it turns out, you can not use the message functions while in the initialization phase, so I started a timer that only executes once to take care of the initial messaging.
I was having the same problem while sending the app_message_outbox_send() command which was getting called by to the Up_button_click handler.
The following initialization code in the Init() method fixed it for me.
Look at the "Register message handlers" & "Init buffers"
void out_sent_handler(DictionaryIterator *sent, void *context){}
static void out_fail_handler(DictionaryIterator *failed, AppMessageResult reason, void* context){}
static void in_received_handler(DictionaryIterator *iter, void* context){}
void in_drop_handler(AppMessageResult reason, void *context){}
static void init() {
// Register message handlers
app_message_register_outbox_sent(out_sent_handler);
app_message_register_inbox_received(in_received_handler);
app_message_register_inbox_dropped(in_drop_handler);
app_message_register_outbox_failed(out_fail_handler);
// Init buffers
app_message_open(64, 64);
// Create main Window element and assign to pointer
s_main_window = window_create();
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
}

Real time java - async event handler fails to fire

The following code is adapted from an example in Real-Time Java Platform Programming by Peter C. Dibble:
import javax.realtime.*;
public class OSTimer {
static volatile boolean cont = true;
public static void main(String[] args) {
AsyncEventHandler handler = new AsyncEventHandler(){
public void handleAsyncEvent() {
System.out.println("Stopping...");
cont = false;
}
}
};
OneShotTimer timer = new OneShotTimer(new RelativeTime(3000, 0), handler);
timer.start();
while(cont){
System.out.println("Running");
if (timer.isRunning()) System.out.println("Timer is running");
try {
Thread.sleep(1000);
} catch(Exception e) { }
}
System.exit(0);
}
The the program is supposed to run for 3 seconds and then exit. However, the output shows that while the timer did indeed stop after 3 seconds, the program continues as usual, i.e. output is:
Running
Timer is running
Running
Timer is running
Running
Timer is running
Running
Running
Running......
Clearly the handler did not fire, and I've no idea why. Another example program involving a periodic timer triggering the handler does work as expected. The program structure is almost the same as the one here.
A few things to try:
Call fire() explicitly on the timer instance to see if you can force things
Try creating your handler by passing in the logic as a Runnable object to the handler. The API is a little unclear on this, but this is how I have specified handlers in the past.
Example:
AsyncEventHandler handler = new AsyncEventHandler(new Runnable() {
public void run() {
System.out.println("Stopping...");
cont = false;
}
});

Sleep call in qthread blocks UI thread

Hi
i am implementing a simple threaded GUI application in QT 4.6.2. I am using QThread without subclassing it. I have made a call to the usleep() function in my start() function this however results in freezing of the GUI. How do i get around this. Below is the code
#ifndef ECGREADER_H
#define ECGREADER_H
#include<QObject>
class ecgreader : public QObject
{
Q_OBJECT
public:
ecgreader(QObject *parent=0);
~ecgreader();
public Q_SLOTS:
void start();
Q_SIGNALS:
void finished();
};
#endif // ECGREADER_H
Below is the start() function
void ecgreader::start()
{
int i= system("ls>output.txt");
SLEEP(10000);
if(i==0)
{
emit finished();
}
}
finally the call to start is made here
void Application::onbtnclicked()
{
QThread* thread=new QThread;
ecgreader* reader=new ecgreader;
reader->moveToThread(thread);
connect(thread,SIGNAL(started()),reader,SLOT(start()));
connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
reader->start();
}
Please help
You have two problems: first you created the thread, but you never started it. Second you are directly calling start() on your reader instead of emiting a signal.
I think what you meant was to call thread->start() instead of reader->start():
void Application::onbtnclicked()
{
QThread* thread=new QThread;
ecgreader* reader=new ecgreader;
reader->moveToThread(thread);
connect(thread,SIGNAL(started()),reader,SLOT(start()));
connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
thread->start();
}

Resources