我试图弄清楚如何将数据发送到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 App获取信息到WinForm的唯一方法是响应循环发送的消息。



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

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

package.appxmanifest

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

最佳答案

您应该能够通过UWP应用在已建立的应用服务连接上发送请求,如下所示:

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


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

connection.RequestReceived += Connection_RequestReceived;


签出this sample,它演示了控制台应用程序和UWP应用程序之间的双向通信。

10-08 14:49