事件及範例

RightClickOccurred 事件

工具本身也支持滑鼠右鍵事件,在表單起始時,確保自定義控制項(strucform )中的 RightClickOccurred 事件以正確的委託類型(EventHandler)定義:

// subscribing to the RightClickOccurred event with the correct event handler
strucForm.RightClickOccurred += strucForm_RightClickOccurred;

將你的方法與事件結合

// have the correct method signature that matches the EventHandler<RightClickEventArgs> delegate
private void strucForm_RightClickOccurred(object sender, RightClickEventArgs e)
{
    // Your event handling code here
    
    // Access the location information
    Point location= e.MouseLocation;

    // Show the context menu at the mouse click location
    contextMenuStrip.Show(strucForm, location);
}

也可以組合方法與事件

// right click event
strucForm.RightClickOccurred += (sender, args) =>
{
    Console.WriteLine("OnRightClickOccurred from program...");
    Point Location= args.MouseLocation;
    // Show the context menu at the mouse click location
    contextMenuStrip.Show(strucForm, Location);
};

OnDataSaved 事件

定義

OnDataSaved 是一個公開的事件,允許外部物件訂閱並在資料成功儲存時被觸發。這個事件使用了 C# 的標準 EventHandler<T>,其中泛型參數為 string,代表所傳遞的資料內容(例如儲存的 JSON 資料)。

宣告方式

csharp複製程式碼public event EventHandler<string> OnDataSaved;

工作流程

  1. 當某些操作需要儲存資料時(如表單內容被覆寫或新增記錄時),程式會執行資料保存邏輯。

  2. 如果儲存成功,會觸發 OnDataSaved 事件並將相關資料(如 JSON 格式的儲存資料)作為參數傳遞給訂閱者。

  3. 訂閱者可以利用該事件來執行進一步的處理,例如更新 UI 或通知使用者。

範例用途

以下範例展示了如何在資料成功儲存時觸發 OnDataSaved 事件:

var overwriteButton = new Button
{
    Text = "覆寫紀錄",
    BackColor = Color.FromArgb(51, 122, 183),
    ForeColor = Color.White
};
overwriteButton.Click += async (s, e) =>
{
    try
    {
        await SaveDocAsync("overwrite");
        string jsonData = await GetJsonTextAsync();
        if (!string.IsNullOrEmpty(jsonData))
        {
            OnDataSaved?.Invoke(this, jsonData); // 觸發事件並傳遞資料
        }
    }
    catch (Exception ex)
    {
        LogErrorToRemoteServer("儲存覆寫紀錄時發生錯誤", $"{ex.Message}");
    }
};

訂閱範例

外部類別可以訂閱 OnDataSaved 事件來接收通知:

var strucForm = new StrucForm();
strucForm.OnDataSaved += (sender, savedData) =>
{
    Console.WriteLine($"資料已成功儲存:{savedData}");
};

Last updated