开发者

Firing custom events / General event handling

开发者 https://www.devze.com 2023-01-08 08:39 出处:网络
I\'m getting into event handling now, and it seems quite confusing to me. See, I come from a web-dev background, so this event stuff is quite new to me.

I'm getting into event handling now, and it seems quite confusing to me. See, I come from a web-dev background, so this event stuff is quite new to me.

I'm developing in C# / VS08 and created my Application in the WinForm-Designer.

Now, I created this program overview;

ProgramContext
 MainForm : Form
 LoginForm : Form

So, what I want to do is when the user clicks "Logout" (What is a menu item in the MainMenu of MainForm), that the application logs out the user.

But how can I access the "Click" event of the logout item from the ProgramContext's view, as there is all the logic of logging in etc.

I tried the following

MenuItem[] findLogout = MainMenuStrip.Items.Find("logoutMenuItem", true); // Throws NullPointerException
findLogout[0].Click += new开发者_JAVA技巧 EventHandler(LogoutClick);

private void LogoutClick(object sender, EventArgs e)
{
 // Logout user
}

But keep getting a NullPointerException at the first line.


Easiest thing to do is to expose an event on MainForm:

public EventHandler LogOut;

Then hook into this from your ProgramContext:

MainForm form = new MainForm();
form.LogOut += new EventHandler(MainForm_LogOut);

void MainForm_LogOut(object sender, EventArgs e)
{
    // Logout
}

Then fire the LogOut button is pressed on the MainMenu using the following code in the Menu Item's click event:

private void LogoutClick(object sender, EventArgs e)
{
    if (LogOut != null)
    {
        LogOut(sender, e);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消