Sutharshan Suthan
Sutharshan Suthan

Reputation: 133

How to access button of opened form?

    private void rbnbtnPageSetup_Click(object sender, EventArgs e)
    {
        if (IsFormOpen(typeof(GUI.Printing)))
        {

        }
        else
        {
            MessageBox.Show("Please Open Printing Form");
        }
    }

IsFormOpen(Type t) is a method that return true if printing Form is open.

I want to open the print preview button in Printing form. Make sure i don't want to open new printing form. My requirement is if printing form is open then press print prieview button of that form.

Method i have used to check form is open or not:

    //Checking Form is open or not
    public bool IsFormOpen(Type formType)
    {
        foreach (Form form in Application.OpenForms)
        {
            if (form.GetType() == formType)
                return true;
        }
        return false;
    }

Upvotes: 0

Views: 130

Answers (2)

gzaxx
gzaxx

Reputation: 17600

Instead of clicking button on another form just move 'PreviewClick' logic to separate method, make it public and fire it.

So in your preview form, create new method:

private void PrintButtonClick(object sender, EventArgs e)
{
     Preview();
}

public void Preview()
{
     //... preview logic here
}

and then you can do this:

private void rbnbtnPageSetup_Click(object sender, EventArgs e)
{
    if (IsFormOpen(typeof(GUI.Printing)))
    {
         var frm = Application.OpenForms.OfType<Form>().FirstOrDefault(x => x.GetType() == typeof(GUI.Printing)); //this retrieves the preview form
         frm.Show();
         frm.Preview();
    }
    else
    {
        MessageBox.Show("Please Open Printing Form");
    }
}

I do not see any problems with my LINQ way but just to be sure use the same approach to get form as to check if it is opened. So change this line

var frm = Application.OpenForms.OfType<Form>().FirstOrDefault(x => x.GetType() == typeof(GUI.Printing)); //this retrieves the preview form

to this: LAST EDIT

GUI.Printing preview = null;
foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(GUI.Printing))
    {
        preview = (GUI.Printing)form;
        break;
    }
}

if (preview == null)
{
    return;
}

preview.Show();
preview.Preview();

This has to work or otherwise something very strange is going on in your code.

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151594

Keep a reference to your printing form, and give it a public method Print() and a public method ShowPrintPreview(). Then whenever you want to print or preview something, you just call the appropriate method.

Upvotes: 1

Related Questions