public static MorphicResult <MorphicUnit, Win32ApiError> GenerateApplicationCommandEvent(IntPtr sourceHwnd, IntPtr targetHwnd, AppCommand appCommand) { var uDevice = ExtendedPInvoke.FAPPCOMMAND_KEY; // "user pressed a key" (i.e. we are generating an app command as a virtual key press) ushort dwKeys = 0; // no virtual mouse/modifier/X keys are down return(AppCommandUtils.GenerateApplicationCommandEvent(sourceHwnd, targetHwnd, dwKeys, uDevice, appCommand)); }
// NOTE: this overload is provided in case the caller doesn't have a window to send the application command from; note that this scenario isn't quite as fail-proof as providing an hwnd (since explorer.exe could be crashed, restarting, etc.) public static MorphicResult <MorphicUnit, Win32ApiError> GenerateApplicationCommandEvent(AppCommand appCommand) { var taskbarHwnd = PInvoke.User32.FindWindow("Shell_TrayWnd", null); if (taskbarHwnd == IntPtr.Zero) { // could not find taskbar window var win32ErrorCode = PInvoke.Kernel32.GetLastError(); return(MorphicResult.ErrorResult(Win32ApiError.Win32Error((uint)win32ErrorCode))); } // NOTE: many implementations of SendMessage(...WM_APPCOMMAND) use a sourceHwnd of IntPtr.Zero; we've chosen to use the taskbar as both source and target hwnd out of an abundance of caution; if this doesn't work well in practice, try following the example of others by setting the sourceHwnd to IntPtr.Zero return(AppCommandUtils.GenerateApplicationCommandEvent(taskbarHwnd, taskbarHwnd, appCommand)); }