How to re-open a minimized Tauri application with Keyboard shortcuts

118 views Asked by At

I am building a small application with Tauri (React). I am unable to open the application when it is minimized.

const handleKeyPress = useCallback(async (event: any) => {
    if (event.ctrlKey && event.key === "t") {
      // Minimize the window
      await appWindow.minimize();
    } else if (event.ctrlKey && event.key === "w") {
      await appWindow.hide();
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", handleKeyPress);
    return () => {
      document.removeEventListener("keydown", handleKeyPress);
    };
  }, [handleKeyPress]);

This is how I can minimize with a shortcut. But unable to setFocus to the minimized app and reopen it again.

2

There are 2 answers

0
Mason Burke On BEST ANSWER

Since the document no longer has focus when it's minimized, it's unable to listen for KeyDown events. Luckily Tauri has the means to register global shortcuts via its globalShortcut API. Your code may look something like this:

import { registerAll } from "@tauri-apps/api/globalShortcut";
import { appWindow } from "@tauri-apps/api/window";
import { useEffect } from "react";

/*...*/

useEffect(() => {
  const registerShortCuts = async () => {
    await registerAll(["t", "w"], async (shortcut) => {
      if (shortcut === "t") await appWindow.minimize();
      else await appWindow.unminimize();
    });
  };

  registerShortCuts();
}, []);

You may want to make your shortcuts more complex so that they do not interfere with the normal use of other applications.

0
DeveloperMindset.com On

For tauri 2.x:

Add shortcut plugin to Cargo.toml:

tauri-plugin-global-shortcut = "v2.0.0-beta.2"

Then call it inside your app builder in lib.rs

.plugin(tauri_plugin_global_shortcut::Builder::new().build())

Add npm library:

npm install @tauri-apps/plugin-global-shortcut

Add the listener:

import { registerAll } from '@tauri-apps/plugin-global-shortcut';

await registerAll(['t','w'], (shortcut) => {
  console.log(`Shortcut ${shortcut} triggered`);
});

And don't forget to set capabilities inside src-tauri/capabilities/main.json:

{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "main-capability",
  "description": "Capability for the main window",
  "windows": ["main"],
  "permissions": [
    "global-shortcut:allow-is-registered",
    "global-shortcut:allow-register",
    "global-shortcut:allow-unregister"
  ]
}