什么是'DispatchedHandler'以及如何在ABI中使用它?

时间:2015-01-31 00:34:56

标签: c++ winapi windows-runtime

将此方法与C ++ / CX一起使用很简单:

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    // Your UI update code goes here!
});

但是我和ABI合作然后事情变得更加复杂。 ' RunAsync'

的方法

ABI::Windows::UI::Core::ICoreDispatcher

作为第二个参数

ABI::Windows::UI::Core::IDispatchedHandler

这是什么意思?这是

中的声明

windows.ui.core.h

namespace ABI {
        namespace Windows {
            namespace UI {
                namespace Core {

                    MIDL_INTERFACE("D1F276C4-98D8-4636-BF49-EB79507548E9")
                    IDispatchedHandler : public IUnknown
                    {
                    public:
                        virtual HRESULT STDMETHODCALLTYPE Invoke( void) = 0;

                    };

                    extern const __declspec(selectany) IID & IID_IDispatchedHandler = __uuidof(IDispatchedHandler);


                }  /* end namespace */
            }  /* end namespace */
        }  /* end namespace */
    }  /* end namespace */

如何将这个漂亮的lambda代码存储在' CX'这个奇怪的界面(似乎不是WinRT组件,继承IUnkown而不是IInspectable)。

1 个答案:

答案 0 :(得分:0)

您必须创建一个实现IDispatchedHandler的类,例如:

class MyDispatchedHandler : public RuntimeClass<
    RuntimeClassFlags<WinRtClassicComMix>,
    IDispatchedHandler>
{
public:
    // Needed for MakeAndInitialize.
    HRESULT RuntimeClassInitialize()
    {
        return S_OK;
    }

    // IDispatchedHandler members.
    virtual HRESULT STDMETHODCALLTYPE Invoke()
    {
        // TODO: Write here the code you need to run in the UI thread.

        return S_OK;
    }
};

然后,传递创建此类的实例并将其传递给RunAsync(),即:

// For simplicity, I omitted error validation.

ComPtr<MyDispatchedHandler> myDispatchedHandler;
MakeAndInitialize<MyDispatchedHandler>(&myDispatchedHandler);

ComPtr<IAsyncAction> asyncAction;

dispatcher->RunAsync(
    CoreDispatcherPriority::CoreDispatcherPriority_Normal,
    myDispatchedHandler.Get(),
    &asyncAction);