防截屏的框架与代码实现
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 );实现步骤
- 获取窗口句柄。
- 调用
GetWindowLongPtr获取当前窗口样式。 - 设置
WS_EX_NOACTIVATE标志位。 - 调用
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.注意事项
- 系统兼容性:不同操作系统和版本对防截屏的支持可能不同,需测试验证。
- 用户体验:防截屏可能影响用户操作体验,需谨慎使用。
- 安全性:防截屏不能完全阻止所有截屏行为,需结合其他安全措施。
以上是防截屏的框架与代码实现,具体实现方式需根据目标平台和需求选择。
参考来源
- HarmonyOS开发,防截屏&防录屏的api介绍及功能实现
- Windows防截屏
- 鸿蒙6.0应用开发——实现防截屏功能
- uni-app 实现安卓防截屏(整个应用或某个页面)
- IOS APP画面防截屏