鸿蒙中开启关闭防截屏录屏

发布于:2024-12-18 ⋅ 阅读:(128) ⋅ 点赞:(0)

1.申请权限

  "requestPermissions": [
      {
        "name": "ohos.permission.PRIVACY_WINDOW"
      },
    ],

2.ui

import { common, OpenLinkOptions, Want } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { window } from '@kit.ArkUI';
import { promptAction } from '@kit.ArkUI';

@Entry()
@Component
struct TransactionHistory {
  async setWindowPrivacyModeTrue(context: Context) {
    let windowClass: window.Window = await window.getLastWindow(context)
    try {
      windowClass.setWindowPrivacyMode(true, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
          if (errCode == 201) {

          }
          return;
        }
        promptAction.showToast({
          message: `已开启 防截屏录屏`,
          duration: 2000,
          bottom: '500lpx'
        });
        console.info('Succeeded in setting the window to privacy mode.');
      });
    } catch (exception) {
      console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
    }
  }

  async setWindowPrivacyModeFalse(context: Context) {
    let windowClass: window.Window = await window.getLastWindow(context)
    try {
      windowClass.setWindowPrivacyMode(false, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
          if (errCode == 201) {

          }
          return;
        }
        promptAction.showToast({
          message: `已关闭 防截屏录屏`,
          duration: 2000,
          bottom: '500lpx'
        });
        console.info('Succeeded in setting the window to privacy mode.');
      });
    } catch (exception) {
      console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
    }
  }

  build() {
    Column() {
      Button('开启防截屏录屏').onClick(() => {
        this.setWindowPrivacyModeTrue(getContext())
      })
      Button('关闭防截屏录屏').onClick(() => {
        this.setWindowPrivacyModeFalse(getContext())
      })
    }.width('100%')
  }
}