簡體   English   中英

c#從DLL調用winform中的代碼

[英]c# Calling back from a DLL a code in the winform

我正在構建許多Winform應用程序,在這些應用程序中我將使用很多垂直菜單(並且由於不存在任何控件,因此我不得不使用基於RadioButtons的代碼動態地構建它們),因此我考慮構建一個單獨的DLL,這將引起注意這些菜單的創建,並且每當我需要那種菜單時都使用此DLL,這是用於動態創建菜單的代碼的安全性:

//Creating a menubutton for each item :
foreach (MenuItem menuItem in _allItems)
{
var menuButton = CreateMenuBottons(menuItem);
_allMenuButtons.Add(menuButton);
}

// Dynamicly create the RadioButton and turn it into a menuButton

private RadioButton CreateMenuBottons(MenuItem item)
{
var index = _allItems.IndexOf(item);
var menuButton = new RadioButton();

menuButton.Appearance = Appearance.Button;
menuButton.AutoSize = true;
menuButton.Dock = DockStyle.Fill;
...
...
...
...
menuButton.Tag = item.Value;
menuButton.UseVisualStyleBackColor = true;

menuButton.CheckedChanged += Radio_CheckedChanged; //My problem is here !!!

return menuButton;

}

這就是我檢測菜單上單擊哪個按鈕的方式:

private void Radio_CheckedChanged(object sender, EventArgs e)
{
var selectedMenuButton = (RadioButton)sender;
if (selectedMenuButton.Checked)
{
// code that will be excuted when we
// click one menuButton (belongs to the DLL)
// How can i point back to the Exe project
// that is using this DLL !
}
}

我的問題是,我將在其他多個項目(winforms)中使用此DLL,並且每個項目中需要執行的代碼將與其余代碼不同,因此如何從DLL中調用winform項目中的方法(無需更改DLL並在每次使用時重新編譯)?

只是代表

您可以定義一個委托,指定要提供的參數

public delegate void MenuButtonClickCallbackDelegate(TypeOfData data);
public MenuButtonClickCallbackDelegate MenuButtonClickCallback;

然后在需要時調用它:

private void Radio_CheckedChanged(object sender, EventArgs e)
{
var selectedMenuButton = (RadioButton)sender;
if (selectedMenuButton.Checked)
{
    if(MenuButtonClickCallback != null)
        MenuButtonClickCallback(parameter);
}
}

這是從exe向MenuButtonClickCallback分配功能的方式:

void MenuButtonClicked(TypeOfData data)
{
}
/*
.
.
.
*/
theObject.MenuButtonClickCallback = MenuButtonClicked;

事件

或者,您可以提供一個事件(如果可能會調用多個方法)。 您必須定義MenuButtonClickCallback如下:

public event MenuButtonClickCallbackDelegate MenuButtonClickCallback;

方法的分配是這樣完成的:

void MenuButtonClicked(TypeOfData data)
{
}
void MenuButtonClickedAnotherMethod(TypeOfData data)
{
}
/*
.
.
.
*/
theObject.MenuButtonClickCallback += MenuButtonClicked;
theObject.MenuButtonClickCallback += MenuButtonClickedAnotherMethod;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM