Flutter窗口钩子插件winhooker的使用

Flutter窗口钩子插件winhooker的使用

winhooker 是一个用于 Flutter 的插件,允许开发者捕获和处理 Windows 系统级别的键盘和鼠标事件。通过该插件,您可以轻松实现全局快捷键监听、全局鼠标事件监听等功能。


获取开始

创建项目

首先,确保您已经安装了 Flutter 和 Dart SDK。然后,创建一个新的 Flutter 项目:

flutter create winhooker_example
cd winhooker_example

添加依赖

pubspec.yaml 文件中添加 winhooker 插件依赖:

dependencies:
  flutter:
    sdk: flutter
  winhooker: ^0.0.1  # 请根据实际版本替换

然后运行以下命令以更新依赖项:

flutter pub get

使用示例

示例代码

以下是一个完整的示例代码,展示了如何使用 winhooker 插件来监听键盘和鼠标事件。

示例代码:lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:winhooker/winhooker.dart';
import 'package:winhooker/winhooker_method_channel.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _winHooker = Winhooker();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 初始化平台状态
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _winHooker.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late Winhooker _winhooker;
  late StreamSubscription keyBoardStreamSubscription;
  StreamSubscription? mouseStreamSubscription;

  @override
  void initState() {
    super.initState();
    _winhooker = Winhooker();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Winhooker 示例'),
      ),
      body: Container(
        color: Colors.white,
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 键盘钩子按钮
            Container(
              height: 50,
              color: Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  MaterialButton(
                    padding: const EdgeInsets.symmetric(horizontal: 40),
                    color: Colors.blue,
                    onPressed: () async {
                      keyBoardStreamSubscription = _winhooker.streamKeyboardHook().listen((event) {
                        print("键盘事件: $event");
                      });
                    },
                    child: const Text("开始键盘钩子", style: TextStyle(color: Colors.white)),
                  ),
                  MaterialButton(
                    padding: const EdgeInsets.symmetric(horizontal: 40),
                    color: Colors.blue,
                    onPressed: () async {
                      keyBoardStreamSubscription.cancel();
                    },
                    child: const Text("停止键盘钩子", style: TextStyle(color: Colors.white)),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 10),
            // 鼠标钩子按钮
            Container(
              color: Colors.white,
              height: 50,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  MaterialButton(
                    padding: const EdgeInsets.symmetric(horizontal: 40),
                    color: Colors.blue,
                    onPressed: () async {
                      if (mouseStreamSubscription != null && mouseStreamSubscription!.isPaused) {
                        mouseStreamSubscription!.resume();
                      } else {
                        mouseStreamSubscription = _winhooker.streamMouseHook().listen((event) {
                          print("鼠标事件: $event");
                        });
                      }
                    },
                    child: const Text("开始鼠标钩子", style: TextStyle(color: Colors.white)),
                  ),
                  MaterialButton(
                    padding: const EdgeInsets.symmetric(horizontal: 40),
                    color: Colors.blue,
                    onPressed: () async {
                      if (mouseStreamSubscription != null) {
                        mouseStreamSubscription!.pause();
                      }
                    },
                    child: const Text("暂停鼠标钩子", style: TextStyle(color: Colors.white)),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

功能说明

键盘钩子

  • 启动键盘钩子:点击“开始键盘钩子”按钮后,会监听所有键盘事件,并打印到控制台。
  • 停止键盘钩子:点击“停止键盘钩子”按钮后,停止监听键盘事件。

鼠标钩子

  • 启动鼠标钩子:点击“开始鼠标钩子”按钮后,会监听所有鼠标事件,并打印到控制台。
  • 暂停鼠标钩子:点击“暂停鼠标钩子”按钮后,暂停监听鼠标事件。

输出示例

当按下键盘或移动鼠标时,控制台将输出类似以下信息:

键盘事件: KeyEvent(keyCode: 65, keyName: "A", isDown: true)
鼠标事件: MouseEvent(x: 100, y: 200, button: Left, isDown: true)

更多关于Flutter窗口钩子插件winhooker的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter窗口钩子插件winhooker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


winhooker 是一个用于在 Flutter 中捕获 Windows 窗口事件的插件。它允许你监听和响应窗口的创建、销毁、焦点变化等事件。下面是如何使用 winhooker 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 winhooker 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  winhooker: ^0.0.1  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在你的 Flutter 应用中,你需要在 main 函数中初始化 winhooker 插件。

import 'package:flutter/material.dart';
import 'package:winhooker/winhooker.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 winhooker
  await Winhooker.initialize();

  runApp(MyApp());
}

3. 监听窗口事件

你可以使用 Winhooker 提供的 API 来监听窗口事件。以下是一个简单的示例,监听窗口的创建和销毁事件:

import 'package:flutter/material.dart';
import 'package:winhooker/winhooker.dart';

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> _events = [];

  [@override](/user/override)
  void initState() {
    super.initState();

    // 监听窗口创建事件
    Winhooker.onWindowCreated.listen((windowHandle) {
      setState(() {
        _events.add('Window Created: $windowHandle');
      });
    });

    // 监听窗口销毁事件
    Winhooker.onWindowDestroyed.listen((windowHandle) {
      setState(() {
        _events.add('Window Destroyed: $windowHandle');
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Winhooker Example'),
        ),
        body: ListView.builder(
          itemCount: _events.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(_events[index]),
            );
          },
        ),
      ),
    );
  }
}
回到顶部