@@ -48,14 +48,16 @@ class TrayManagerPlugin : public flutter::Plugin {
4848 flutter::PluginRegistrarWindows* registrar;
4949 NOTIFYICONDATA nid;
5050 NOTIFYICONIDENTIFIER niif;
51- HMENU hMenu;
51+ // do create pop-up menu only once.
52+ HMENU hMenu = CreatePopupMenu();
5253 bool tray_icon_setted = false ;
5354 UINT windows_taskbar_created_message_id = 0 ;
5455
5556 // The ID of the WindowProc delegate registration.
5657 int window_proc_id = -1 ;
5758
5859 void TrayManagerPlugin::_CreateMenu (HMENU menu, flutter::EncodableMap args);
60+ void TrayManagerPlugin::_ApplyIcon ();
5961
6062 // Called for top-level WindowProc delegation.
6163 std::optional<LRESULT> TrayManagerPlugin::HandleWindowProc (HWND hwnd,
@@ -198,11 +200,10 @@ std::optional<LRESULT> TrayManagerPlugin::HandleWindowProc(HWND hWnd,
198200 return DefWindowProc (hWnd, message, wParam, lParam);
199201 };
200202 } else if (message == windows_taskbar_created_message_id) {
201- if (windows_taskbar_created_message_id != 0 ) {
202- channel->InvokeMethod (" onWindowsTaskbarCreated" ,
203- std::make_unique<flutter::EncodableValue>(nullptr ));
204- // race condition?
203+ if (windows_taskbar_created_message_id != 0 && tray_icon_setted) {
204+ // restore the icon with the existing resource.
205205 tray_icon_setted = false ;
206+ _ApplyIcon ();
206207 }
207208 }
208209 return result;
@@ -233,22 +234,25 @@ void TrayManagerPlugin::SetIcon(
233234
234235 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t >> converter;
235236
236- HICON hIcon = static_cast <HICON>(
237+ nid. hIcon = static_cast <HICON>(
237238 LoadImage (nullptr , (LPCWSTR)(converter.from_bytes (iconPath).c_str ()),
238239 IMAGE_ICON, GetSystemMetrics (SM_CXSMICON),
239240 GetSystemMetrics (SM_CYSMICON), LR_LOADFROMFILE));
240241
242+ _ApplyIcon ();
243+
244+ result->Success (flutter::EncodableValue (true ));
245+ }
246+
247+ void TrayManagerPlugin::_ApplyIcon () {
241248 if (tray_icon_setted) {
242- nid.hIcon = hIcon;
243249 Shell_NotifyIcon (NIM_MODIFY, &nid);
244250 } else {
245251 nid.cbSize = sizeof (NOTIFYICONDATA);
246252 nid.hWnd = GetMainWindow ();
247253 nid.uCallbackMessage = WM_MYMESSAGE;
248- nid.hIcon = hIcon;
249254 nid.uFlags = NIF_MESSAGE | NIF_ICON;
250255 Shell_NotifyIcon (NIM_ADD, &nid);
251- hMenu = CreatePopupMenu ();
252256 }
253257
254258 niif.cbSize = sizeof (NOTIFYICONIDENTIFIER);
@@ -257,8 +261,6 @@ void TrayManagerPlugin::SetIcon(
257261 niif.guidItem = GUID_NULL;
258262
259263 tray_icon_setted = true ;
260-
261- result->Success (flutter::EncodableValue (true ));
262264}
263265
264266void TrayManagerPlugin::SetToolTip (
@@ -285,7 +287,6 @@ void TrayManagerPlugin::SetContextMenu(
285287 const flutter::EncodableMap& args =
286288 std::get<flutter::EncodableMap>(*method_call.arguments ());
287289
288- hMenu = CreatePopupMenu ();
289290 _CreateMenu (hMenu, std::get<flutter::EncodableMap>(
290291 args.at (flutter::EncodableValue (" menu" ))));
291292
0 commit comments