How to show Windows Form Element Host's Message Box as Modal?

687 views Asked by At

I have windows form application in C#. I have class library for WPF user control. And I am using that in Windows Form App using Element Host. Now in WPF User control i need to show one message using MessageBox. it's working but displayed modeless on Main Form of Windows Form Application. I want to Show this Message box as model.

Any help please.

Edits:

let me Explain by example: I have “WindowsFormApp1” Another is “WPFUserCtrlLib” which is class library. And it has UserControl named as “WPFUserCtrl” so I have “WPFUserCtrl.xaml” and “WPFUserCtrl.xaml.cs” Files. In WindowsFormApp1 I have MainForm named “Form1”. In Form1 I am using “WPFUserCtrl” using Element Host. Now there is some logic resides in “WPFUserCtrl.xaml.cs” say

String ErrorMsg=“Error There”;
if(condition)
{
//Do Task
}
else
{
MessageBox.Show(ErrorMsg);
}

So here I need to show ErrorMsg. When this MessageBox is displayed, it is modeless as I am able to access controls on “Form1” like menus, buttons and all.

2

There are 2 answers

0
aru On BEST ANSWER

I have tried lot. Couldn't get solution so posted question here and continued to try again with diff approach. And Now I found the solution.

Solution is: use Dispatcher.Invoke

if(condition)
{
    //Do Task
}
else
{
    Dispatcher.Invoke(new Action(() => {
                MessageBox.Show(ErrorMsg);
            })
            );
}

Now my MessageBox is model.

1
DerApe On

Did you set the owner of the WPF window to the winforms window?

According to this link that is necessary in order to make the modal dialog work within winforms.

var window = new WpfWindow(); 

var helper = new WindowInteropHelper(window);
helper.Owner = this.Handle; 

window.ShowDialog();