I have created a tray application for controlling some hardware components. How can I invoke the UI thread without a main form or control?
The tray app is started with Application.Run(new MyTrayApp())
:
class MyTrayApp : ApplicationContext
{
private NotifyIcon trayIcon;
public MyTrayApp()
{
trayIcon = new NotifyIcon()
{
Icon = Resources.app_icon,
ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Exit", Exit)
}),
Visible = true
};
// context is still null here
var context = SynchronizationContext.Current;
// but I want to invoke UI thread in hardware events
MyHardWareController controller= new MyHardWareController(context);
}
void Exit(object sender, EventArgs e)
{
// context is accessible here because this is a UI event
// too late tho
var context = SynchronizationContext.Current;
trayIcon.Visible = false;
Application.Exit();
}
}
Control.Invoke()
is not available as there are no controls
- Searching suggests that
SynchronizationContext.Current
should be saved for later invoke but there is no ApplicationContext.Load()
event...?
- I've noticed that
MainForm
is null
in the whole cycle. I wonder how does SynchronizationContext
initialized in this case?
Edit:
Just to add some background info on why I would like to invoke UI thread. It is because System.Threading.ThreadStateException
will be thrown when attempt to access Windows resources such as Clipboard
or SendKeys
in another thread:
HResult=0x80131520
Message=Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
Source=System.Windows.Forms
StackTrace:
...
It's another can of worms but just for information:
[STAThreadAttribute]
is already set for Main function (no effect)
- Creating a new STA thread would result in anti-virus deleting my application upon compile
Thus Form.Invoke()
or the equivalent to invoke main thread should be the easiest.
Edit 2:
Add a gist for reproducing the error:
https://gist.github.com/jki21/eb950df7b88c06cc5c6d46f105335bbf
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…