I'm coding in Microsoft Visual Studio, C#, WPF.
My main window (MainForm.cs) has BorderStyle=none and it should load several UserControls into a panel (that covers almost the entire window). All are in the same namespace. Some elements in these UserControls need to have a MouseDown event (in their respective designer files) that calls a function in the MainForm.cs (that function makes the mousedown'd element drag the entire window).
This is just an example. Other items in the UserControl will need to call different functions from the MainForm.cs into a EventHandler or a MouseEventHandler. Basically I need that an event will call (not sure if this is the right term in this context) a function from the main window.
I've seen many solutions for this, but none have worked (maybe because I didn't search with the correct terms, or maybe because I didn't implement them well in my code).
Some relevant code from the main window:
public partial class MainForm : Form
{
private const int HTCAPTION = 0x2;
private const int WM_NCLBUTTONDOWN = 0xA1;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();
public void OnMousedown(object sender, MouseEventArgs e)
{
// Allow the form to be draggable
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
}
}
}
... and some current code from a usercontrol designer file:
partial class CopperOrNonCopperSelection
{
private void InitializeComponent()
{
// SelectCopperOrNonCopperLabel is a label in the usercontrol. There's more code here to customize this label.
this.SelectCopperOrNonCopperLabel.MouseDown += new System.Windows.Forms.MouseEventHandler(((MainForm)Parent).OnMousedown);
}
}
This code works in the MainForm designer file, when I want to apply the same function on a different item in MainForm.cs when MouseDown'd:
this.ElementName.MouseDown += new System.Windows.Forms.MouseEventHandler((this.OnMousedown);
Obviously simply changing "this" to "MainForm" in the usercontrol designer file doesn't work. I've actually tried so many other options (and, to be honest, without understanding them) but I can't remember them off-hand.
Somehow the MouseDown event should do whatever in the OnMousedown function from MainForm. I've seen many users saying that this is bad practice, so I'm open to other suggestions (other than copy-pasting the function to the usercontrol).
With the current code mentioned above, I get an Delegate to an instance method cannot have null 'this'.'
error on the ... (((MainForm)Parent).OnMousedown)
code.