SiC99
SiC99

Reputation: 37

How can I find the form name of the previous form?

I have a dialogue window (just a form) class which can be called by several forms. I want the title of this dialogue to change dependent on which form called it.

Is there a way, within the dialogue class, of finding out the form name of the form which called it (without altering the code of the several forms which can call it)?

Upvotes: 2

Views: 869

Answers (4)

Pikoh
Pikoh

Reputation: 7703

I have tried it just with a simple example, but using GetWindowLongPtr you can get the parent form of your dialog. First of all you have to add this definitions in your dialog:

[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
static extern IntPtr GetWindowLongPtr(IntPtr hWnd, GWL nIndex);

public enum GWL
{
    GWL_WNDPROC = (-4),
    GWL_HINSTANCE = (-6),
    GWL_HWNDPARENT = (-8),
    GWL_STYLE = (-16),
    GWL_EXSTYLE = (-20),
    GWL_USERDATA = (-21),
    GWL_ID = (-12)
}

And then,in your dialog, you can do this:

private void Form2_Load(object sender, EventArgs e)
{
    IntPtr parentHandle = GetWindowLongPtr(this.Handle, GWL.GWL_HWNDPARENT);
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {   
        if (frm.Handle==parentHandle)
        {
            Console.WriteLine(frm.Name); //this is your parent form
        }

    }
}

Anyway, I think it's easier to just call ShowDialog(this), but if you can't really change the calling forms, this method may be handy.

Upvotes: 1

Tatranskymedved
Tatranskymedved

Reputation: 4371

Assuming that You are creating other dialogs(forms) from the main form, You can do:

public partial class MyForm : Form
{
    //Some code
    public void OpenDialog_Click(...)
    {
        MyOtherForm form = new MyOtherForm();
        form.Parent = this;
        form.ShowDialog();
    }
}

And Your 2nd form:

public partial class MyOtherForm : Form
{
    public MyOtherForm()
    {
        var parent = this.Parent as Form;
        if(parent != null)
            this.Title = parent.Title;
    }
}

Upvotes: 0

huse.ckr
huse.ckr

Reputation: 530

FormCollection may help you:

FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
    MessageBox.Show(frm.Name.ToString());
}

Upvotes: 0

GuidoG
GuidoG

Reputation: 12014

You can try this on the dialogform, make sure you do this before the dialogform becomes active to prevent it from finding itself.

public Form GetActiveForm()
{
    Form activeForm = Form.ActiveForm;

    if (activeForm.IsMdiContainer && activeForm.ActiveMdiChild != null)
    {
        activeForm = activeForm.ActiveMdiChild;
    }
    return activeForm;
}

Upvotes: 0

Related Questions