【问题标题】:Use WinForm as AppService for UWP使用 WinForm 作为 UWP 的 AppService
【发布时间】:2018-09-28 10:09:47
【问题描述】:

我试图弄清楚如何将数据发送到我的 WinForm 组件,而不必总是回复 WinForm 发送的消息。我知道可以在 UWP App 的package.appxmanifest 中设置 AppService 名称等。但是,在 WinForms 这样的 Win32 环境中,这相当于什么。

是否需要任何代码来帮助获得答案?

谢谢

编辑

目前,我的 UWP 应用每隔几毫秒响应一次从我的 WinForm 组件发送的消息。

App.xaml.cs

protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    base.OnBackgroundActivated(args);
    if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails)
    {
        appServiceDeferral = args.TaskInstance.GetDeferral();
        args.TaskInstance.Canceled += OnTaskCanceled; // Associate a cancellation handler with the background task.

        AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails;
        Connection = details.AppServiceConnection;
        Connection.RequestReceived += (new MainPage()).Connection_OnRequestReceived; 
    }
}

MainPage.xaml.cs

public async void Connection_OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
    // write setting to stop timer
    localSettings.Values["Win32Working"] = "True";

    // read content
    if (args.Request.Message.ContainsKey("content"))
    {
        object message = null;
        args.Request.Message.TryGetValue("content", out message);
        // if message is an int[]
        if (message is int[])
        {
            // init field vars
            int indexInArray = 0;
            bool newTest1On = false;
            bool newTest2On = false;
            bool newTest3On = false;

            foreach (int trueorfalse in (int[])message)
            {
                // set bool state based on index
                switch (indexInArray)
                {
                    case 0:
                        newCapsOn = Convert.ToBoolean(trueorfalse);
                        localSettings.Values["Test1"] = (Convert.ToBoolean(trueorfalse)).ToString();
                        break;
                    case 1:
                        newNumOn = Convert.ToBoolean(trueorfalse);
                        localSettings.Values["Test2"] = (Convert.ToBoolean(trueorfalse)).ToString();
                        break;
                    case 2:
                        newScrollOn = Convert.ToBoolean(trueorfalse);
                        localSettings.Values["Test3"] = (Convert.ToBoolean(trueorfalse)).ToString();
                        break;
                    default:
                        break;
                }
                indexInArray++;
            }

            if (newTest1On != Test1On || newTest2On != Test2On || newTest3On != Test3On)
                localSettings.Values["updateUI"] = true.ToString();

            // update bools
            Test1On = newTest1On;
            Test2On = newTest2On;
            Test3On = neTest3On;

            // if exit requested
            if (Convert.ToBoolean(localSettings.Values["sendExit"]))
            {
                // tell WinForm to exit
                ValueSet messageExit = new ValueSet();
                messageExit.Add("exit", null);
                AppServiceResponseStatus responseStatus = await args.Request.SendResponseAsync(messageExit);
                localSettings.Values["sendExit"] = false.ToString();
                localSettings.Values["Win32Working"] = false.ToString();
            }
        }
    }
    else if (args.Request.Message.ContainsKey("request"))
    {
        if (!Convert.ToBoolean(localSettings.Values["sendExit"]))
        {
            // send current settings as response
            AppServiceResponseStatus responseStatus = await args.Request.SendResponseAsync(UpdateWin32());
        }
        else
        {
            // tell WinForm to exit
            ValueSet message = new ValueSet();
            message.Add("exit", null);
            AppServiceResponseStatus responseStatus = await args.Request.SendResponseAsync(message);
            localSettings.Values["sendExit"] = false.ToString();
            localSettings.Values["Win32Working"] = false.ToString();
        }
    }
    else if (args.Request.Message.ContainsKey("exit"))
    {
        // exit
        Application.Current.Exit();
    }
}

我的 WinForm 代码:​​

private async void threadCommunicationWinFrmAndUWP_Run()
{
    bool askForInfo = false;

    DoWork:

    ValueSet message = new ValueSet();
    if (!askForInfo) { message.Add("content", notifyIconsLogic.GetStatuses()); askForInfo = true; }
    else { message.Add("request", ""); askForInfo = false; }

    #region SendToUWP

    // if connection isn't inited
    if (connection == null)
    {
        // init
        connection = new AppServiceConnection();
        connection.PackageFamilyName = Package.Current.Id.FamilyName;
        connection.AppServiceName = "NotifyIconsUWP";

        // attempt connection 
        AppServiceConnectionStatus connectionStatus = await connection.OpenAsync();

        // if UWP isn't running
        if (connectionStatus == AppServiceConnectionStatus.AppUnavailable) return;
    }

    AppServiceResponse serviceResponse = await connection.SendMessageAsync(message);

    // if UWP isn't running
    if (serviceResponse.Status == AppServiceResponseStatus.Failure) return;

    // get response
    if (serviceResponse.Message.ContainsKey("content"))
    {
        object newMessage = null;
        serviceResponse.Message.TryGetValue("content", out newMessage);
        // if message is an int[]
        if (newMessage is int[])
        {
            // init field vars
            int indexInArray = 0;
            bool showTest1 = false;
            bool showTest2 = false;
            bool showTest3 = false;

            foreach (int trueorfalse in (int[])newMessage)
            {
                // set bool state based on index
                switch (indexInArray)
                {
                    case 0:
                        showTest1 = Convert.ToBoolean(trueorfalse);
                        break;
                    case 1:
                        showTest2 = Convert.ToBoolean(trueorfalse);
                        break;
                    case 2:
                        showTest3 = Convert.ToBoolean(trueorfalse);
                        break;
                    default:
                        break;
                }
                indexInArray++;
            }

            notifyIconsLogic.SetChecker(showTest1, showTest2, showTest3);
        }
    }
    if (serviceResponse.Message.ContainsKey("exit")) Exit();
    #endregion

    goto DoWork;
}

这会过度增加 CPU 使用率。关键是,目前我从 UWP 应用程序向 WinForm 获取信息的唯一方法是响应循环发送的消息。

问题

如何在不只响应循环发送的消息的情况下,从 UWP App 向 WinForm 发送消息?因为,我想消除对循环的依赖(CPU 用途)。

换句话说:如何让package.appxmanifest 的结果在 WinForms 中“工作”?

package.appxmanifest

<Extensions>
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="NotifyIconsUWP" />
    </uap:Extension>
    <desktop:Extension Category="windows.fullTrustProcess" Executable="Win32\NotifyIconsComponent.exe" />
</Extensions>

【问题讨论】:

  • 您是否正在寻找在应用程序(Windows 应用程序/控制台应用程序/Windows 服务)中托管 WFC 服务或 WEB API 服务?
  • 不,它只是我用来在系统托盘中显示 NotifyIcons 的普通 WinForm。
  • 不清楚你在问什么。请编辑问题并添加更多详细信息并详细说明。
  • 请查看我的编辑,如果您仍然不理解,请告诉我
  • 有什么想法吗?

标签: c# winforms uwp


【解决方案1】:

您应该能够从 UWP 应用程序对已建立的应用程序服务连接发送请求,如下所示:

AppServiceResponse response = await App.Connection.SendMessageAsync(valueSet);

然后通过附加事件处理程序在 Windows 窗体应用程序中接收此消息:

connection.RequestReceived += Connection_RequestReceived;

查看this sample,它演示了控制台应用和 UWP 应用之间的两种通信方式。

【讨论】:

  • 感谢您的回答。我遵循示例的逻辑并建立了连接。但是当我调用 SendMessageAsync 时,代码只是通过它而不做任何事情。没有错误,也没有响应。我试图打开连接,但它返回给我连接已经打开 AppServiceConnectionStatus connectionStatus = await App.Connection.OpenAsync();
  • 是否有可能我没有在 Winforms 应用程序上正确实现 Connection_RequestReceived?我仍然应该得到一个错误或一些通知。
  • 我有一个问题,如果我收到来自 Win32 应用程序的任何消息,我将无法从 UWP 应用程序发送消息。 UWP 应用程序将滞后并停止工作。有人可以给我建议吗?
  • 如果你在 GitHub 上创建一个简单的 repo,我可以尝试调试一下
猜你喜欢
  • 2019-03-25
  • 2018-06-06
  • 2018-02-23
  • 2021-08-28
  • 2017-02-13
  • 2019-02-21
  • 2021-12-04
  • 2017-07-06
  • 2020-08-29
相关资源
最近更新 更多