共用方式為


如何:新增命令傳送至 Windows Form 控制項

CWinFormsView 會將命令和更新命令 UI 訊息路由傳送至使用者控制項,以允許它處理 MFC 命令(例如框架功能表項目和工具列按鈕)。

使用者控制項會使用 ICommandTarget::Initialize 將命令來源物件的參考儲存在 中 m_CmdSrc ,如下列範例所示。 若要使用 ICommandTarget ,您必須新增 mfcmifc80.dll 的參考。

CWinFormsView 將這些通知轉送至受管理的使用者控制項,以處理數個常見的 MFC 檢視通知。 這些通知包括 OnInitialUpdate、 OnUpdate OnActivateView 方法。

本主題假設您先前 已完成如何:在對話方塊中 建立使用者控制項和主機, 以及如何:建立使用者控制項和主機 MDI 檢視

建立 MFC 主應用程式

  1. 開啟您在 How to: Create the User Control and Host in a Dialog Box 建立的 Windows Forms 控制項程式庫。

  2. 新增 mfcmifc80.dll 的參考,您可以在方案總管 以滑鼠右鍵按一下專案節點,選取 [新增 ]、 [參考 ],然後流覽至 Microsoft Visual Studio 10.0\VC\atlmfc\lib。

  3. 開啟 UserControl1.Designer.cs,並新增下列 using 語句:

    using Microsoft.VisualC.MFC;
    
  4. 此外,在 UserControl1.Designer.cs 中,變更這一行:

    partial class UserControl1
    

    轉換為:

    partial class UserControl1 : System.Windows.Forms.UserControl, ICommandTarget
    
  5. 將這個 新增為 類別定義 UserControl1 的第一行:

    private ICommandSource m_CmdSrc;
    
  6. 將下列方法定義新增至 UserControl1 (我們將在下一個步驟中建立 MFC 控制項的識別碼):

    public void Initialize (ICommandSource cmdSrc)
    {
       m_CmdSrc = cmdSrc;
       // need ID of control in MFC dialog and callback function
       m_CmdSrc.AddCommandHandler(32771, new CommandHandler (singleMenuHandler));
    }
    
    private void singleMenuHandler (uint cmdUI)
    {
       // User command handler code
       System.Windows.Forms.MessageBox.Show("Custom menu option was clicked.");
    }
    
  7. 開啟您在 How to: Create the User Control and Host MDI View 中建立的 MFC 應用程式。

  8. 新增將叫用 singleMenuHandler 的功能表選項。

    移至 [資源檢視 ] [Ctrl+Shift+E],展開 [功能表 ] 資料夾,然後按兩下 [IDR_MFC02TYPE ]。 這會顯示功能表編輯器。

    在 [檢視 ] 功能表底部 新增功能表選項。 請注意 [屬性 ] 視窗中功能表選項 的識別碼。 儲存檔案。

    方案總管 中,開啟 Resource.h 檔案、複製您剛才新增之功能表選項的 Initialize 識別碼值,然後將該值貼上為 m_CmdSrc.AddCommandHandler C# 專案方法中呼叫的第一個參數( 32771 如有必要取代)。

  9. 建置並執行專案。

    在 [建置] 功能表上,按一下 [建置方案]。

    在 [偵錯] 功能表上,按一下 [ 開始但不偵錯 ]。

    選取您新增的功能表選項。 請注意,呼叫 .dll 中的 方法。

另請參閱

將 Windows Form 使用者控制項裝載為 MFC 檢視
ICommandSource 介面
ICommandTarget 介面