防截屏的框架与代码实现

1. HarmonyOS 防截屏实现

在 HarmonyOS 中,防截屏功能主要通过 window 模块中的 setWindowPrivacyMode 方法实现。该方法可以设置窗口为隐私模式,从而防止截屏或录屏。

实现方式一:在 onWindowStageCreate 回调中设置主窗口为隐私模式

// 在页面的 onWindowStageCreate 回调中设置主窗口为隐私模式
@Override
public void onWindowStageCreate(Window window) {
    // 设置窗口为隐私模式
    window.setWindowPrivacyMode(true);
}

实现方式二:进入页面开启隐私模式,离开页面取消

// 在 onPageShow 方法中开启隐私模式
@Override
public void onPageShow() {
    Window window = getWindow();
    if (window != null) {
        window.setWindowPrivacyMode(true);
    }
}

// 在 onPageHide 方法中取消隐私模式
@Override
public void onPageHide() {
    Window window = getWindow();
    if (window != null) {
        window.setWindowPrivacyMode(false);
    }
}

权限声明

在 config.json 文件中添加以下权限:

{
  "permissions": [
    "ohos.permission.PRIVACY_WINDOW"
  ]
}

2. Windows 防截屏实现

在 Windows 系统中,可以通过调用系统 API 来实现防截屏功能。主要使用的是 SetWindowLongPtr 和 GetWindowLongPtr 函数,结合 GWL_EXSTYLE 参数来设置窗口样式。

API 原型与参数

LONG SetWindowLongPtr(
  HWND hWnd,
  int nIdx,
  LONG_PTR dwNewLong
);

LONG GetWindowLongPtr(
  HWND hWnd,
  int nIdx
);

实现步骤

  1. 获取窗口句柄。
  2. 调用 GetWindowLongPtr 获取当前窗口样式。
  3. 设置 WS_EX_NOACTIVATE 标志位。
  4. 调用 SetWindowLongPtr 更新窗口样式。

示例代码(C++)

#include <windows.h>

void SetNoCapture(HWND hWnd) {
    LONG style = GetWindowLongPtr(hWnd, GWL_EXSTYLE);
    style |= WS_EX_NOACTIVATE;
    SetWindowLongPtr(hWnd, GWL_EXSTYLE, style);
    SetWindowPos(hWnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
}

3. iOS 防截屏实现

在 iOS 应用中,可以通过设置 UITextField 的 secureTextEntry 属性为 true,以防止截屏或录屏时显示内容。

实现方式一:设置 UITextField 为安全输入

let textField = UITextField()
textField.secureTextEntry = true

实现方式二:自定义视图防截屏

对于非故事板的 ViewController,可以在 viewDidLoad 中替换 self.view 为自定义视图:

override func viewDidLoad() {
    super.viewDidLoad()
    self.view = SecurityScreenShortView()
}

对于故事板的 ViewController,可以在 Interface Builder 中将 UIView 类更改为 SecurityScreenShortView。

自定义视图实现

import UIKit

class SecurityScreenShortView: UIView {
    override var canBecomeKeyView: Bool {
        return false
    }

    override var isHidden: Bool {
        get {
            return super.isHidden
        }
        set {
            super.isHidden = newValue
        }
    }

    override var alpha: CGFloat {
        get {
            return super.alpha
        }
        set {
            super.alpha = newValue
        }
    }
}

4. uni-app 防截屏实现

在 uni-app 中,可以通过在 App.vue 中全局禁止截屏,或在某个页面中动态控制。

全局禁止截屏

// App.vue
onLaunch() {
  // 禁止截屏
  plus.android.addIntentFilter("android.intent.action.SCREENSHOT");
}

页面级防截屏

// 在页面的 onShow 生命周期中启用防截屏
onShow() {
  plus.android.addIntentFilter("android.intent.action.SCREENSHOT");
}

// 在页面的 onHide 生命周期中恢复
onHide() {
  plus.android.removeIntentFilter("android.intent.action.SCREENSHOT");
}

5. 注意事项

  • 系统兼容性:不同操作系统和版本对防截屏的支持可能不同,需测试验证。
  • 用户体验:防截屏可能影响用户操作体验,需谨慎使用。
  • 安全性:防截屏不能完全阻止所有截屏行为,需结合其他安全措施。

以上是防截屏的框架与代码实现,具体实现方式需根据目标平台和需求选择。


参考来源

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐