目录

Unity Android 之 获取蓝牙Bluetooth 的状态,设置的蓝牙Bluetooth 的开关状态,并监听蓝牙Bluetooth 的状态变化方法整理

一、简单介绍

二、实现原理

三、注意事项

四、效果预览

五、实现步骤

Android 端:

Unity 端

六、关键代码

Android 端

Unity 端

一、简单介绍
Unity Android 开发上会用到的技术简单整理,方便自己日后查看,能帮助到大家就更好了。

本节介绍,Unity 开发中,把从 Android 获取手机设备的蓝牙Bluetooth的状态,并设置蓝牙Bluetooth开关,监听蓝牙Bluetooth的状态变化的方法整理封装给Unity调用,方法不唯一,欢迎指正。

二、实现原理
1、获取蓝牙适配器 BluetoothAdapter.getDefaultAdapter()

2、bluetoothAdapter.isEnabled() 获取蓝牙的状态

3、bluetoothAdapter.enable()/bluetoothAdapter.disable() 设置蓝牙开关状态

4、使用广播监听 BluetoothAdapter.ACTION_STATE_CHANGED 蓝牙状态变化

5、打包成 aar ,Unity 调用 aar 的封装好的接口

三、注意事项
1、添加蓝牙权限

四、效果预览

五、实现步骤
Android 端:
1、新建一个Android Library 模块,其他默认设置就好

2、在模块中新建两个脚本,BluetoothStateUtil 封装各个功能,BluetoothStateInterface 一个接口函数,蓝牙状态变化的接口

3、脚本编辑 OK,Build - Make Module ‘xxxx’,打包 aar

4、打包成功,build 文件夹outputs/aar中就会 有对应的 aar 生成

Unity 端
1、把 Android 打包的 aar 导入 Unity

2、在场景中布局UI,Toggle 显示设置 蓝牙状态

3、在 Unity工程中,新建脚本,编辑对应功能

4、把 TestBluetoothStateWrapper 挂载到场景中,并对应赋值

5、运行场景,没有问题,即可打包到真机上测试

6、真机上的测试效果如上

六、关键代码
Android 端
1、BluetoothStateUtil

package com.example.bluetoothstatewrapper;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

public class BluetoothStateUtil {

private static final String TAG = "Main_BluetoothStateUtil";

private BluetoothAdapter bluetoothAdapter;
private BluetoothStateBroadcastReceive mReceive;
private Context mContext;
private BluetoothStateInterface mBluetoothStateInterface;

/**
 * 初始化
 */
public void Init(BluetoothStateInterface bluetoothStateInterface){

    // 获得蓝牙适配器对象
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mContext = getActivity();
    mBluetoothStateInterface = bluetoothStateInterface;
}

/**
 * 获取蓝牙状态
 * @return
 */
public boolean getBlueToothState() {
    // 获取蓝牙状态
    return bluetoothAdapter.isEnabled();
}

/**
 * 开启蓝牙
 * @return
 */
public boolean openBlueTooth() {
    if (getBlueToothState()) return true;
    // 打开蓝牙
    return bluetoothAdapter.enable();
}

/**
 * 关闭蓝牙
 * @return
 */
public boolean colseBlueTooth() {
    if (!getBlueToothState()) return true;
    // 关闭蓝牙
    return bluetoothAdapter.disable();
}

// 调用系统的请求打开蓝牙
public void gotoSystem(Context context){
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    context.startActivity(intent);
}

/**
 * 注册监听蓝牙变化
 */
public void registerBluetoothReceiver(){
    if(mReceive == null){
        mReceive = new BluetoothStateBroadcastReceive();
    }
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
    intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
    mContext.registerReceiver(mReceive, intentFilter);
}

/**
 * 取消监听蓝牙变化
 */
public void unregisterBluetoothReceiver(){
    if(mReceive != null){
        mContext.unregisterReceiver(mReceive);
        mReceive = null;
    }
}

/**
 * 蓝牙状态变化监听
 */
class BluetoothStateBroadcastReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        switch (action){
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                //Toast.makeText(context , "蓝牙设备:" + device.getName() + "已连接", Toast.LENGTH_SHORT).show();
                Log.i(TAG, "onReceive: "+"蓝牙设备:" + device.getName() + "已连接");
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                //Toast.makeText(context , "蓝牙设备:" + device.getName() + "已断开", Toast.LENGTH_SHORT).show();
                Log.i(TAG, "onReceive: "+"蓝牙设备:" + device.getName() + "已断开");
                break;
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState){
                    case BluetoothAdapter.STATE_OFF:
                        //Toast.makeText(context , "蓝牙已关闭", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "onReceive: "+"蓝牙已关闭:" );
                        mBluetoothStateInterface.onBluetoothStateOFF();
                        break;
                    case BluetoothAdapter.STATE_ON:
                        //Toast.makeText(context , "蓝牙已开启"  , Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "onReceive: "+"蓝牙已开启:");
                        mBluetoothStateInterface.onBluetoothStateON();
                        break;
                }
                break;
        }
    }
}


// 设置一个 Activity 参数
private Activity _unityActivity;

// 通过反射获取 Unity 的 Activity 的上下文
Activity getActivity(){

    if(null == _unityActivity){

        try{

            Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");

            Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);

            _unityActivity = activity;

        }catch (ClassNotFoundException e){

            e.printStackTrace();

        }catch (IllegalAccessException e){

            e.printStackTrace();

        }catch (NoSuchFieldException e){

            e.printStackTrace();

        }

    }

    return _unityActivity;

}

}

2、BluetoothStateInterface

package com.example.bluetoothstatewrapper;

public interface BluetoothStateInterface {

void onBluetoothStateON();
void onBluetoothStateOFF();

}

3、AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.bluetoothstatewrapper" >

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Unity 端
1、BluetoothStateWrapper

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AndroidWrapper {

/// <summary>
/// 蓝牙状态封装
/// 使用说明
/// 1、首先初始化,绑定监听事件
/// 2、可获取蓝牙状态,设置蓝牙状态
/// 3、获得监听结果
/// </summary>
public class BluetoothStateWrapper : MonoSingleton<BluetoothStateWrapper>
{

    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="VoiceVolumnChangedListener"></param>
    public void Init(Action OnBluetoothStateONListener, Action OnBluetoothStateOFFListener)
    {

if UNITY_EDITOR

else

        MAndroidJavaObject.Call("Init",new BluetoothStateInterface(OnBluetoothStateONListener, OnBluetoothStateOFFListener));
        registerBluetoothReceiver();

endif

    }

    /// <summary>
    /// 获得蓝牙状态
    /// </summary>
    /// <returns></returns>
    public bool getBlueToothState()
    {
        
        return MAndroidJavaObject.Call<bool>("getBlueToothState");
    }

    /// <summary>
    /// 开启蓝牙
    /// </summary>
    /// <returns></returns>
    public bool openBlueTooth()
    {
        
        return MAndroidJavaObject.Call<bool>("openBlueTooth");
    }

    /// <summary>
    /// 关闭蓝牙
    /// </summary>
    /// <returns></returns>
    public bool colseBlueTooth()
    {
        
        return MAndroidJavaObject.Call<bool>("colseBlueTooth");
    }

region 私有方法

    /// <summary>
    /// 注册蓝牙状态监听
    /// </summary>
    void registerBluetoothReceiver()
    {
        MAndroidJavaObject.Call("registerBluetoothReceiver");
    }

    /// <summary>
    /// 取消注册蓝牙状态监听
    /// </summary>
    void unregisterBluetoothReceiver()
    {
        MAndroidJavaObject.Call("unregisterBluetoothReceiver");
    }


    protected override void OnDestroy()
    {
        unregisterBluetoothReceiver();
        base.OnDestroy();
    }

endregion

region 私有变量

    AndroidJavaObject _mAndroidJavaObject;

    public AndroidJavaObject MAndroidJavaObject
    {
        get
        {
            if (_mAndroidJavaObject == null)
            {
                _mAndroidJavaObject = new AndroidJavaObject("com.example.bluetoothstatewrapper.BluetoothStateUtil");
            }

            return _mAndroidJavaObject;
        }
    }

endregion

}

}

2、BluetoothStateInterface

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AndroidWrapper
{

/// <summary>
/// 蓝牙状态监听接口
/// </summary>
public class BluetoothStateInterface : AndroidJavaProxy
{
    /// <summary>
    /// 蓝牙变化委托事件
    /// </summary>
    Action _mBluetoothStateON;
    Action _mBluetoothStateOFF;

    public BluetoothStateInterface(Action mBluetoothStateON, Action mBluetoothStateOFF) : base("com.example.bluetoothstatewrapper.BluetoothStateInterface")
    {
        _mBluetoothStateON = mBluetoothStateON;
        _mBluetoothStateOFF = mBluetoothStateOFF;
    }

    /// <summary>
    /// 蓝牙打开事件监听
    /// </summary>
    public void onBluetoothStateON()
    {

        if (_mBluetoothStateON != null)
        {
            _mBluetoothStateON();
        }

        Debug.Log(GetType() + "/onBluetoothStateON()/ 蓝牙开启事件");
    }

    /// <summary>
    /// 蓝牙关闭事件监听
    /// </summary>
    public void onBluetoothStateOFF()
    {
        if (_mBluetoothStateOFF != null)
        {
            _mBluetoothStateOFF();
        }

        Debug.Log(GetType() + "/onBluetoothStateOFF()/ 蓝牙关闭事件");
    }
}

}

3、TestBluetoothStateWrapper

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AndroidWrapper;
using UnityEngine.UI;

public class TestBluetoothStateWrapper : MonoBehaviour
{

public Toggle BTState_Toggle;

// Start is called before the first frame update
void Start()
{
    BluetoothStateWrapper.Instance.Init(SetOnToggle, SetOffToggle);
    InitToggle();
}

/// <summary>
/// 初始化
/// </summary>
void InitToggle() {

if UNITY_EDITOR

    // 获取当前状态
    SetIsOnToggle(Random.Range(0,2) ==0 ? false:true);
    // 设置监听事件
    BTState_Toggle.onValueChanged.AddListener((isOn) => {
       
    });

else

    // 获取当前状态
    SetIsOnToggle(BluetoothStateWrapper.Instance.getBlueToothState());
    // 设置监听事件
    BTState_Toggle.onValueChanged.AddListener((isOn)=> {
        if (isOn == true)
        {
            BluetoothStateWrapper.Instance.openBlueTooth();

        }
        else {
            BluetoothStateWrapper.Instance.colseBlueTooth();
        }
    });

endif

}

void SetOnToggle() {
    SetIsOnToggle(true);
}

void SetOffToggle()
{
    SetIsOnToggle(false);
}

void SetIsOnToggle(bool isOn) {
    BTState_Toggle.isOn = isOn;
}

}

4、MonoSingleton

using UnityEngine;

public abstract class MonoSingleton : MonoBehaviour where T : MonoBehaviour
{

private static T instance = null;

private static readonly object locker = new object();

private static bool bAppQuitting;

public static T Instance
{
    get
    {
        if (bAppQuitting)
        {
            instance = null;
            return instance;
        }

        lock (locker)
        {
            if (instance == null)
            {
                instance = FindObjectOfType<T>();
                if (FindObjectsOfType<T>().Length > 1)
                {
                    Debug.LogError("不应该存在多个单例!");
                    return instance;
                }

                if (instance == null)
                {
                    var singleton = new GameObject();
                    instance = singleton.AddComponent<T>();
                    singleton.name = "(singleton)" + typeof(T);
                    singleton.hideFlags = HideFlags.None;
                    DontDestroyOnLoad(singleton);
                }
                else
                    DontDestroyOnLoad(instance.gameObject);
            }
            instance.hideFlags = HideFlags.None;
            return instance;
        }
    }
}

protected virtual void Awake()
{
    bAppQuitting = false;
}

protected virtual void OnDestroy()
{
    bAppQuitting = true;
}

}
————————————————
版权声明:本文为CSDN博主「仙魁XAN」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u014361280/article/details/108217598

报错描述
我们安装Docker Desktop的时候,他会问我们是否需要使用WSL2(基于Windows的Linux子系统),如果我们不适用,就会使用Hyper-v虚拟机运行,不过相比于虚拟机,子系统在性能方面更加出色。在我们选择使用WSL2之后,并且我们也确定打开了如下图所示的Windows功能(如果没有打开,请先百度如何打开wsl。)

请输入图片描述

还是会出现一个下图所示的报错。

请输入图片描述

解决报错
更加报错提示,猜测可能是我们使用的wsl2版本老了,需要我们自己手动更新一下,我们根据提示去微软官网下载最新版的wsl2安装后即可正常打开。
更新包下载链接。

https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi
————————————————
版权声明:本文为CSDN博主「寻_觅」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39611230/article/details/108625840

地球人和火星人都知道,Process类既可以获取正在运行的进程,也可以启动一个新的进程。在79.77%应用场合,我们只需要让目标进程顺利启动就完事了,至于它执行了啥,有没有出错,啥时候退出就不管了。

但是,在某些情况下,启动新进程后,还希望能向目标进程传送数据,或者实时读取来自新进程的信息。比如,启动一个安装程序,安装程序会向标准流写入安装进度,然后调用方可以从标准流中读取进度,以达到实时监控安装进度的目的。

Process类公开三个标准流属性:

StandardInput——输入流。类型是Writer,为啥是writer呢,因为这个标准流是相对于被启动的进程而言的,流动方向是从调用方流向目标进程,所以是写入数据,即将内容发送到目标进程。

StandardOutput——输出流。即目标进程对外输出的内容,流动方向是从目标进程流向调用方,因此,对调用者来说,是读取,故其类型为Reader。

StandardError——和输入流差不多,只是它专用于输出错误。错误信息是目标进程输出的,所以,对调用者来说还是读取者。

综上所述,只要启动新进程后,从StandardOutput属性在得到一个StreamReader对象,然后建立一个循环,不断地从流中读取内容,就能够实时获得最新状态了。

其实,还有更好办的方法,Process类有个BeginOutputReadLine方法,调用后,会自动异步读取数据,一旦收到目标进程传回的数据,就会引发OutputDataReceived事。所以,我们在代码中只要处理这个事件就可以接收实时信息了。

咱们来做个例子吧。假设我弄一个程序,只负责在后台安装,每处理完一个进度,就会向标准流写入进度信息,这样调用者就能实时监控安装进度了。

首先完成被调用的项目,项目类型为Windows应用程序项目。

不管它,反正就是一个标准的.exe文件,这个项目我是先建个空白项目,然后手动设置的。

每个可执行程序都必须至少有一个Main方法。主要的处理代码都在这里完成,只要Main方法执行完,进程就会退出了。

复制代码

    static void Main()
    {
        StreamWriter writer = null;
        Stream outStream = Console.OpenStandardOutput();
        writer = new StreamWriter(outStream);

        int n = 0;
        while (n <= 100)
        {
            Thread.Sleep(30);
            writer.WriteLine(n);
            writer.Flush();
            n++;
        }
        writer.Close();
        Environment.ExitCode = 0;
    }

复制代码
这里用到了Console类,别以为它只能耍控制台应用程序,其实Console类还包括标准输入输出的操作。要调用OpenStandardOutput方法获取标准输出流,然后就可以写入内容了。

由于Process类的StandarOutput属性或OutputDataReceived事件,都是用字符串来传递的,所以上面代码中,咱们也用StreamWriter来写数据。

不过要注意一定,每写一回都要记得Flush一次,这样写入的内容才会让调用方及时收到。如果不Flush的话,写入的内容会放在缓冲区中,直接流关闭或执行Flush时才会真正发送到标准流上,所以,每写完一次都调用一下Flush方法,确保调用方能够实时收到信息。

最后那一行Environment.ExitCode = 0 表示进程退出时返回退出码0,即正常退出。因为我这个Main是返回void的,所以要用Enviroment类的ExitCode来设置。当然了,你还可以把Main方法改为返回int类型的值,然后直接 return 0 就行了。

好,被调用进程项目完成,现在做调用者项目,它是一个WPF项目。在这个时代,写Windows桌面应用都应优先用WPF,因为WPF是牛逼层面的东东。

XAML代码就不贴了,直接讲核心代码。

我用了个进度条来实时显示进度,而Process类的OutputDataReceived事件是异步引发的,要在事件处理中更新进度条,需要借助Dispatcher来代理调用。

不过,在这个例子中并不需要,因为有一个很NX的类,专门用来处理进度的,就是Progress,这个类可以绑定一个回调的委托,用它来更新UI是不需要Dispatcher来调度的,只要Progress实例是在UI线程上创建的即可(忘了说明这句,多谢网友在评论中补充)。

        IProgress<int> progress;

        progress = new Progress<int>(p =>
        {
            pb.Value = p;
        });

在声明变量的时候,应用 IProcess 接口来声明,T是表示进度的类型,Progress类是显示实现了IProgress接口的,为了能够直接调用Report方法报告进度,应当用IProgress接口来声明变量。

下面代码启动刚刚写的那个进程,并监视状态信息。

复制代码

        Process p = new Process();
        p.StartInfo.FileName = "..\\..\\..\\Demo\\bin\\Debug\\Demo.exe";
        p.StartInfo.UseShellExecute = false; //必须为false
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.CreateNoWindow = true;
        p.EnableRaisingEvents = true; //必须为true

        p.OutputDataReceived += OnDataReceived;
        p.Exited += OnExited;
        p.Start();
        p.BeginOutputReadLine();

复制代码
实例化Process后,要设置StartInfo相关参数,FileName是要执行进程的exe文件。

注意:

UseShellExecute必须为false,不然无法在代码中读标准。

RedirectStandardOutput必须为true,这样我们才能在代码中访问标准流。

EnableRaisingEvents必须为true,这样才会引发OutputDataReceived和Exited

事件,否则事件不会发生。

CreateNoWindow表示不显示目标程序的窗口,这个你自己看着办,这里我不让它显示窗口,因为这个程序本来就没有窗口。

一定要在Start方法之后调用BeginOutputReadLine方法,一定要在 Start 和 BeginOutputReadLine方法调用前处理OutputDataReceived事件。为啥,自己想吧,这太简单了,不脱裤子怎么拉屎,除非你不穿裤子。

在OnDataReceived方法中读出数据,并转化为int类型,因为刚才上面的那个项目中,是把一个int值写入流的,所以这里读出来的值是可以转换为int类型的。

    private void OnDataReceived(object sender, DataReceivedEventArgs e)
    {
        int p = Convert.ToInt32(e.Data);
        progress.Report(p);
    }

直接调用IProgress的Report方法就能报告进度了。

本来,是可以调用 System.Diagnostics.Process.WaitForExit()方法来等待进程执行完的,但是,由于这个方法是同步调用的,它会让UI线程塞车,导致UI无法即时响应,体验不好。所以改为处理Exited事件,这个事件会在进程退出后异步调用,不会让UI线程塞车,所以处理它较好。

现在,运行例子,会看以下效果。

WPF 透明窗口可以调整尺寸(通过拖拽窗口边缘)
本文遵循 CC 4.0 BY-SA 版权协议
作者:絮大王

通过这篇文章,我们可以实现:

让WPF的透明窗口可以通过拖拽窗口的边缘,自由的调整尺寸。

我们可以通过拖拽窗口的上方,来移动窗口。

我们可以禁止窗口拖到屏幕边缘时自动最大化。

还可以等比例的改变窗口的大小。

还可以等比例的改变窗口中控件的大小

参考文章
AllowsTransparency=“True” 怎么放大缩小窗体
作者:不灬赖
原文地址:https://blog.csdn.net/LJianDong/article/details/99844199

C# WPF 如何禁止窗口拖到屏幕边缘自动最大化
作者:Bird鸟人
原文地址:https://blog.csdn.net/wcc27857285/article/details/78223901

WPF窗口比例如何保持恒定?
作者:a7066163、Hauk
原文地址:https://bbs.csdn.net/topics/390257164

文章目录
WPF 透明窗口可以调整尺寸(通过拖拽窗口边缘)
参考文章
创建1个“透明窗口”
通过拖拽调整“透明窗口”的尺寸
通过拖拽移动“透明窗口”
禁止窗口自动最大化
等比例的改变窗口的大小
等比例的改变窗口中控件的大小
完整代码

创建1个“透明窗口”
“透明窗口”指的是Window.AllowsTransparency属性为true的窗口。
但是想要Window.AllowsTransparency=“True”,我们需要让Window.WindowStyle="None"。
如果Window.WindowStyle="None",我们就不能够再通过拖拽窗口的边缘,改变窗口的尺寸了;也不能通过拖拽窗口的上方,来移动窗口的位置了。
那怎么办呢?
我们一步一步来,首先我们需要创建1个透明窗口,作为演示。

第1步:我们创建1个新的WPF工程。

现在窗口是这样的 ↓

第2步:设置窗口的背景为透明色。

第3步:但是,我们可以看到,现在窗口的背景是黑色的,并没有变透明,为什么呢?
因为,我们没有允许窗口可以是透明的。
我们在Window控件中,设置AllowsTransparency="True",就可以允许窗口变透明啦!
但是这样运行时会报错,因为如果AllowsTransparency="True",那么WindowStyle属性必须为None!
我们在Window控件中,设置WindowStyle=“None”,这样一来,我们就得到了一个完全透明的窗口啦!

因为窗口是完全透明的,所以我们完全看不到窗口啦!

第4步:我们往窗口里加入一点东西(不然我们什么都看不见啦)。
这里我们在窗口中加入一个白色的背景,并给背景一个圆角,并且让背景有个好看的阴影。

为了方便观察,我们把窗口放到一个白色区域中。

第5步:我们在窗口中,再放入一个按钮。
透明窗口就创建好啦!

代码 (MainWindow.xaml):

<Window x:Class="ResizeTransparentWindow.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ResizeTransparentWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800"
    

    Background="Transparent"
    AllowsTransparency="True"
    WindowStyle="None">



<!--内容(Content)-->
<Grid>

    <!--背景(Background)-->
    <Border Margin="10" Background="White" CornerRadius="25">
        <Border.Effect>
            <DropShadowEffect Direction="0" ShadowDepth="0" BlurRadius="20" 
                              Opacity="0.25" Color="#FF5B5B5B"></DropShadowEffect>
        </Border.Effect>
    </Border>

    <!--按钮(Button)-->
    <Button Width="400" Height="200">
        <TextBlock Width="400" Height="100" TextAlignment="Center"
                   FontSize="70" FontFamily="Source Han Sans CN Medium"
                   Text="Hello"/>
    </Button>

</Grid>

通过拖拽调整“透明窗口”的尺寸
现在,我们没有办法通过拖拽窗口的边缘,调整透明窗口的尺寸。
怎么办呢?
别担心,我们可以使用WindowChrome类。这样我们既能让窗口透明,又能实现缩放窗口!

如果你想了解更多关于WindowChrome类的信息,可以查看微软的官方文档:
https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.shell.windowchrome?view=netframework-4.8

第1步:在Window控件中,创建1个WindowChrome。

第2步:此时,我们可以看到,我们把鼠标移动到窗口边缘拖动后,就已经可以改变窗口的大小啦!

第3步:为了更加完美,我们还可以设置下WindowChrome的CaptionHeight属性和ResizeBorderThickness属性。

CaptionHeight属性:设置标题栏的高度。
ResizeBorderThickness属性:设置拖拽调整窗口区域的宽度(如果你的窗口有阴影的话,可以把这个值调整的更大一点)

代码 (MainWindow.xaml):

<Window x:Class="ResizeTransparentWindow.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ResizeTransparentWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800"
    

    Background="Transparent"
    AllowsTransparency="True"
    WindowStyle="None">


<!--WindowChrome-->
<WindowChrome.WindowChrome>
    <WindowChrome CaptionHeight="0" ResizeBorderThickness="20"/>
</WindowChrome.WindowChrome>


<!--内容(Content)-->
<Grid>

    <!--背景(Background)-->
    <Border Margin="10" Background="White" CornerRadius="25">
        <Border.Effect>
            <DropShadowEffect Direction="0" ShadowDepth="0" BlurRadius="20" 
                              Opacity="0.25" Color="#FF5B5B5B"></DropShadowEffect>
        </Border.Effect>
    </Border>

    <!--按钮(Button)-->
    <Button Width="400" Height="200">
        <TextBlock Width="400" Height="100" TextAlignment="Center"
                   FontSize="70" FontFamily="Source Han Sans CN Medium"
                   Text="Hello"/>
    </Button>

</Grid>

通过拖拽移动“透明窗口”
因为我们设置了Window控件的WindowStyle="None",因此我们现在没有办法通过拖拽来移动窗口。
怎么办呢?
这个特别简单!
我们只需要在按下鼠标的时候,调用Window的DragMove()方法,就可以啦!

第1步:我们创建1个Border,命名为TopBorder。
我们希望当我们按住这个Border的时候,就可以拖动窗口。

第2步:注册TopBorder的MouseLeftButtonDown事件。
(当我们在TopBorder控件身上按下鼠标左键时,就会触发这个MouseLeftButtonDown事件)

第3步:我们在MainWindow.cs中,这样写。

Window类的DragMove()方法,用于当鼠标左键按下后,移动鼠标可以拖动窗口。

第4步:现在我们就可以随意的拖动窗口啦!

代码 (MainWindow.xaml):

<Window x:Class="ResizeTransparentWindow.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ResizeTransparentWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800"
    

    Background="Transparent"
    AllowsTransparency="True"
    WindowStyle="None">


<!--WindowChrome-->
<WindowChrome.WindowChrome>
    <WindowChrome CaptionHeight="0" ResizeBorderThickness="20"/>
</WindowChrome.WindowChrome>


<!--内容(Content)-->
<Grid>

    <!--背景(Background)-->
    <Border Margin="10" Background="White" CornerRadius="25">
        <Border.Effect>
            <DropShadowEffect Direction="0" ShadowDepth="0" BlurRadius="20" 
                              Opacity="0.25" Color="#FF5B5B5B"></DropShadowEffect>
        </Border.Effect>
    </Border>

    <!--按钮(Button)-->
    <Button Width="400" Height="200">
        <TextBlock Width="400" Height="100" TextAlignment="Center"
                   FontSize="70" FontFamily="Source Han Sans CN Medium"
                   Text="Hello"/>
    </Button>

    <!--拖拽窗口的区域(Border:For dragging windows)-->
    <Border Name="TopBorder" Width="780" Height="100"
            VerticalAlignment="Top" Margin="0,10,0,0"
            Background="White" Opacity="0" Cursor="Hand"
            
            MouseLeftButtonDown="TopBorder_OnMouseLeftButtonDown"/>

</Grid>

代码 (MainWindow.cs):

using System.Windows;
using System.Windows.Input;

namespace ResizeTransparentWindow
{

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }



    /// <summary>
    /// 当用鼠标左键点击TopBorder控件时,触发此方法
    /// (This method is triggered when the TopBorder control is clicked with the left mouse button)
    /// </summary>
    private void TopBorder_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        /* 当点击拖拽区域的时候,让窗口跟着移动
         (When clicking the drag area, make the window follow) */
        DragMove();
    }

}

}

禁止窗口自动最大化
现在我们的窗口拖拽到屏幕上方时,会自动最大化。
我们可以不最大化窗口吗?
当然可以!
Bird鸟人大佬用了一种非常巧妙的方法实现了这个功能。

原文地址:https://blog.csdn.net/wcc27857285/article/details/78223901
1
思路:

因为拖到屏幕边缘自动最大化,有个必要条件是鼠标按下去,然后拖。

我们可以利用这个间隙将ResizeMode设置为NoResize,然后鼠标放开之后再把ResizeMode设置回CanResize,就可以啦!

代码 (MainWindow.cs):

using System.Windows;
using System.Windows.Input;

namespace ResizeTransparentWindow
{

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }



    /// <summary>
    /// 当用鼠标左键点击TopBorder控件时,触发此方法
    /// (This method is triggered when the TopBorder control is clicked with the left mouse button)
    /// </summary>
    private void TopBorder_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {

        /* 如何在Window.ResizeMode属性为CanResize的时候,阻止窗口拖动到屏幕边缘自动最大化。
           (When the Window.ResizeMode property is CanResize, 
           when the window is dragged to the edge of the screen, 
           it prevents the window from automatically maximizing.)*/
        if (e.ChangedButton == MouseButton.Left)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                var windowMode = this.ResizeMode;
                if (this.ResizeMode != ResizeMode.NoResize)
                {
                    this.ResizeMode = ResizeMode.NoResize;
                }

                this.UpdateLayout();


                /* 当点击拖拽区域的时候,让窗口跟着移动
                (When clicking the drag area, make the window follow) */
                DragMove();


                if (this.ResizeMode != windowMode)
                {
                    this.ResizeMode = windowMode;
                }

                this.UpdateLayout();
            }
        }
    }

}

}

等比例的改变窗口的大小
那我们可以在拖动鼠标调整窗口大小时,等比例的放大/缩小窗口吗?
比如,可以一直让窗口的比例为4比3吗?
当然可以哒!
这里参考了a7066163、Hauk的方法。
使用这种方法,不仅可以按照比例缩放窗口,还可以避免闪烁的问题!

原文地址:https://bbs.csdn.net/topics/390257164
思路:

【首先Hauk给出了自己的思路】:
拖拉时显示窗口内容 不勾选时:一次拖动只触发一次SizeChanged事件
拖拉时显示窗口内容 勾选时:一次拖动只触发 N 次SizeChanged事件(n=newsize-oldsize)

触发太频繁所以界面更新有点不对劲。
可以使用timer来延迟更新,等用户拖好了来。

【然后a7066163在Hauk想法的基础上做了更改】:
虽然在在鼠标释放的慢的情况下,窗口会退回原来的大小,所以我只在处理鼠标释放的事件就行了。
不过貌似自带边框的鼠标事件不属于窗口事件,最后我直接捕获WM_EXITSIZEMOVE消息,重载了窗口消息处理函数。
通过定时器和WM_EXITSIZEMOVE消息处理的双重保证下,大致能实现窗口比例实时恒定的效果。

效果:

代码 (MainWindow.cs):

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

namespace ResizeTransparentWindow
{

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }



    //最后的宽度(Last Width)
    private int LastWidth;

    //最后的高度(Last Height)
    private int LastHeight;

    //这个属性是指 窗口的宽度和高度的比例(宽度/高度)(4:3)
    //This property refers to the aspect ratio (width / height) of the window (4: 3)
    private float AspectRatio = 4.0f / 3.0f;



    /// <summary>
    /// 捕获窗口拖拉消息
    /// (Capturing window drag messages)
    /// </summary>
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        HwndSource source = HwndSource.FromVisual(this) as HwndSource;
        if (source != null)
        {
            source.AddHook(new HwndSourceHook(WinProc));
        }
    }

    public const Int32 WM_EXITSIZEMOVE = 0x0232;

    /// <summary>
    /// 重载窗口消息处理函数
    /// (Overload window message processing function)
    /// </summary>
    private IntPtr WinProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, ref Boolean handled)
    {
        IntPtr result = IntPtr.Zero;
        switch (msg)
        {
            //处理窗口消息 (Handle window messages)
            case WM_EXITSIZEMOVE:
            {
                //上下拖拉窗口 (Drag window vertically)
                if (this.Height != LastHeight)
                {
                    this.Width = this.Height * AspectRatio;
                }
                // 左右拖拉窗口 (Drag window horizontally)
                else if (this.Width != LastWidth)
                {
                    this.Height = this.Width / AspectRatio;
                }

                LastWidth = (int)this.Width;
                LastHeight = (int)this.Height;
                break;
            }
        }

        return result;
    }
}

}

等比例的改变窗口中控件的大小
那我们可以在更改窗口大小时,等比例的更改窗口中控件的大小吗?
当然可以啦!
这里我们用Viewbox控件,就可以实现这个功能啦!

第1步:我们只需要把所有的控件都放进Viewbox控件中。

第2步:然后,设置Viewbox的Stretch属性为UniformToFill

第3步:现在,我们缩放窗口时,窗口中的内容也会自动等比例进行缩放啦!

代码 (MainWindow.xaml):

<Window x:Class="ResizeTransparentWindow.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ResizeTransparentWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800"
    

    Background="Transparent"
    AllowsTransparency="True"
    WindowStyle="None">


<!--WindowChrome-->
<WindowChrome.WindowChrome>
    <WindowChrome CaptionHeight="0" ResizeBorderThickness="20"/>
</WindowChrome.WindowChrome>


<!--Viewbox-->
<Viewbox Stretch="UniformToFill">

    <!--内容(Content)-->
    <Grid Width="800" Height="600">

        <!--背景(Background)-->
        <Border Margin="10" Background="White" CornerRadius="25">
            <Border.Effect>
                <DropShadowEffect Direction="0" ShadowDepth="0" BlurRadius="20" 
                                  Opacity="0.25" Color="#FF5B5B5B">        
                </DropShadowEffect>
            </Border.Effect>
        </Border>

        <!--按钮(Button)-->
        <Button Width="400" Height="200">
            <TextBlock Width="400" Height="100" TextAlignment="Center"
                       FontSize="70" FontFamily="Source Han Sans CN Medium"
                       Text="Hello"/>
        </Button>

    </Grid>

</Viewbox>

完整代码
MainWindow.xaml:

<Window x:Class="ResizeTransparentWindow.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ResizeTransparentWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800"
    

    Background="Transparent"
    AllowsTransparency="True"
    WindowStyle="None">


<!--WindowChrome-->
<WindowChrome.WindowChrome>
    <WindowChrome CaptionHeight="0" ResizeBorderThickness="20"/>
</WindowChrome.WindowChrome>


<!--Viewbox-->
<Viewbox Stretch="UniformToFill">

    <!--内容(Content)-->
    <Grid Width="800" Height="600">

        <!--背景(Background)-->
        <Border Margin="10" Background="White" CornerRadius="25">
            <Border.Effect>
                <DropShadowEffect Direction="0" ShadowDepth="0" BlurRadius="20" 
                                  Opacity="0.25" Color="#FF5B5B5B"></DropShadowEffect>
            </Border.Effect>
        </Border>

        <!--按钮(Button)-->
        <Button Width="400" Height="200">
            <TextBlock Width="400" Height="100" TextAlignment="Center"
                       FontSize="70" FontFamily="Source Han Sans CN Medium"
                       Text="Hello"/>
        </Button>

        <!--拖拽窗口的区域(Border:For dragging windows)-->
        <Border Name="TopBorder" Width="780" Height="100"
                VerticalAlignment="Top" Margin="0,10,0,0"
                Background="White" Opacity="0" Cursor="Hand"
            
                MouseLeftButtonDown="TopBorder_OnMouseLeftButtonDown"/>

    </Grid>

</Viewbox>

MainWindow.cs:

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

namespace ResizeTransparentWindow
{

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }



    #region [拖动窗口 (Drag Move Window)]

    /// <summary>
    /// 当用鼠标左键点击TopBorder控件时,触发此方法
    /// (This method is triggered when the TopBorder control is clicked with the left mouse button)
    /// </summary>
    private void TopBorder_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        /* 当点击拖拽区域的时候,让窗口跟着移动
           (When clicking the drag area, make the window follow) */
        DragMove();
    }

    #endregion


    #region [等比例调整窗口尺寸(Proportional Resize window)]

    //最后的宽度(Last Width)
    private int LastWidth;

    //最后的高度(Last Height)
    private int LastHeight;

    //这个属性是指 窗口的宽度和高度的比例(宽度/高度)(4:3)
    //This property refers to the aspect ratio (width / height) of the window (4: 3)
    private float AspectRatio = 4.0f / 3.0f;



    /// <summary>
    /// 捕获窗口拖拉消息
    /// (Capturing window drag messages)
    /// </summary>
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        HwndSource source = HwndSource.FromVisual(this) as HwndSource;
        if (source != null)
        {
            source.AddHook(new HwndSourceHook(WinProc));
        }
    }

    public const Int32 WM_EXITSIZEMOVE = 0x0232;

    /// <summary>
    /// 重载窗口消息处理函数
    /// (Overload window message processing function)
    /// </summary>
    private IntPtr WinProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, ref Boolean handled)
    {
        IntPtr result = IntPtr.Zero;
        switch (msg)
        {
            //处理窗口消息 (Handle window messages)
            case WM_EXITSIZEMOVE:
            {
                //上下拖拉窗口 (Drag window vertically)
                if (this.Height != LastHeight)
                {
                    this.Width = this.Height * AspectRatio;
                }
                // 左右拖拉窗口 (Drag window horizontally)
                else if (this.Width != LastWidth)
                {
                    this.Height = this.Width / AspectRatio;
                }

                LastWidth = (int) this.Width;
                LastHeight = (int) this.Height;
                break;
            }
        }

        return result;
    }


    #endregion



}

}
————————————————
版权声明:本文为CSDN博主「絮大王」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xu1295921025/article/details/103982787