0

在本机 sample_extension 示例中,我添加了一个函数来获取当前活动窗口的标题。在飞镖内部,我想定期调用并打印 getActivetWindowTitle

import "sample_extension.dart";
import "dart:async";

void main() {
  var isLittleEndian = SysInfo.isLittleEndian;
  var pageSize = SysInfo.pageSize;
  var sizeOfInt = SysInfo.sizeOfInt;
  var version = SysInfo.version;

  print('Dart VM (${sizeOfInt * 8} bit): $version');
  print('Page size: $pageSize KB');
  print('Endianness: ${isLittleEndian ? 'Little-endian' : 'Big-endian'}');


  new Timer.periodic(new Duration(seconds:1), (timer) => pr() );

}

void pr(){
  var activeWindow = SysInfo.activeWindow;
  print('Active window: $activeWindow');
}

我的飞镖文件 sample_extension.dart 是

library sample_extension;

import "dart-ext:sample_extension";

class SysInfo {
  //<se>
  static bool isLittleEndian = _isLittleEndian();
  static final int pageSize = _getPageSize();
  static final int sizeOfInt = _getSizeOfInt();
  static final String version = _getVersionString();

  static bool _isLittleEndian() native "IsLittleEndian";
  static int _getPageSize() native "GetPageSize";
  static int _getSizeOfInt() native "GetSizeOfInt";
  static String _getVersionString() native "GetVersionString";
  //</se>
  //<aui>
  static final String activeWindow = _getActiveWindowString();
  static String _getActiveWindowString() native "GetActiveWindowString";
  //</aui>
}

额外的 cc 部分是

void GetActiveWindowString(Dart_NativeArguments arguments) {
  Dart_Handle result;
  HWND hwnd;
  LPTSTR lpString;

  Dart_EnterScope();
  hwnd=GetForegroundWindow(); 
  GetWindowText(hwnd, lpString, 128);
  result = Dart_NewStringFromCString(lpString);

  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

我添加了函数查找函数列表

 {"GetActiveWindowString", GetActiveWindowString},

加载 dartapp 时,我得到了正确的活动窗口。

但是在运行时,程序只会打印启动时初始化的值。不是实际的活动窗口。

我究竟做错了什么?

4

1 回答 1

4

activeWindow的被标记为finalA final variable can be set only once;这意味着它在初始化后不会改变,并且它在开始时被初始化为getActiveWindowString()那个时刻的值。

尝试这个:

static String get activeWindow => _getActiveWindowString();

activeWindow现在是一个在调用时返回活动窗口的属性。

编辑:

实现中有一个bug _getActiveWindowString

LPTSTR lpString; // lpString is not initialized and points to random location
...
GetWindowText(hwnd, lpString, 128); // overrides the random location

它应该是:

TCHAR lpString[128];
于 2013-05-22T09:59:27.280 回答