I have a main window which has some menu buttons leading off onto other WPF windows.
I'm having a problem with the code behind the WPF when it crashes.
VS debugger is always showing the crash coming from my 'form.ShowDialog()' instead of the code thats actually creating the crash.
See image.
From the output I can tell its me trying to read one of my SQL database entries which is null.
My question, why does the debugger show this position form.ShowDialog() and not the actual code that broke eg
j.Status = Convert.ToInt32(reader["Status"]);
You can pinpoint easier why the dialog fails by looking at the initialization. In the dialog you are trying to display with ShowDialog(), change the code behind constructor and add a try catch. The dialog encounters an exception and cannot succesfully complete InitializeComponent() e.g:
try {
InitializeComponent();
}
catch (Exception err) {
Debug.Writeline(err);
}
Inspect why the dialog cannot initialize with a breakpoint in the catch clause.
Related
The following code formats the ComboBox background color in a WPF Flow Document.
Try
objHold = New Object
objHold = objCombo.Template.FindName("PART_EditableTextBox", objCombo)
tbTemp = New TextBox
tbTemp = objHold
objCheck = New Object
objCheck = tbTemp.Template.FindName("PART_ContentHost", tbTemp)
If objCheck.GetType = GetType(ScrollViewer) Then
svTemp = New ScrollViewer
svTemp = objCheck
With svTemp
.Background = New SolidColorBrush(ColorConverter.ConvertFromString(strTheme(11)))
End With
End If
Catch ex As Exception
MsgBox(ex.Message & " " & ex.StackTrace, vbExclamation, "Operation Failed!")
End Try
It doesn't do this alone, but it's part of a loop that functions properly EXCEPT for this part:
When the system first attempts to format a combo box, it traverses the template in an attempt to locate where to format the background color.
The first element it reaches is the "PART_EditableTextBox" which almost invariably goes off without a hitch.
When the system attempts to get the "PART_ContentHost" it crashes, displaying "Object Reference not set to an instance of an object," and the affected line of code.
After the first failure on any combo box in the loop, the procedure SUCCEEDS.
The procedure will successfully locate the "PART_ContentHost" and transfer it to the ScrollViewer object.
Once the ScrollViewer is working, the rest of the program mysteriously becomes able to set the background of the combo box.
This is, of course, only able to happen after announcing that it failed.
To the best of my knowledge, it literally HAS to announce its failure in order to succeed. Attempting to eliminate Try, Catch ex As Exception, and End Try doesn't work. Once Try..Catch..End Try is gone, the program will execute without formatting any combo boxes.
Commenting out the message box is also not the answer. It just causes the program to skip formatting any combo boxes.
I'm not finding any way to test for a null reference without crashing. When I attempt to test for an error condition before there's an actual error, it either triggers a message box on that line, or the whole program just skips the part about formatting combo boxes at all.
Remember, with everything in place as-is, the program does run, and does successfully update the background color of any combo box it finds in the loop. It just doesn't do it without throwing a temper tantrum. When I launch testing in Visual Studio, sometimes the message box will appear as few as once per Flow Document, but when I run the .exe file from the folder, it will display a message box for each combo box it finds, but sometimes more.
It's the flurry of message boxes I want to avoid, not the entire functionality of the program. Is there a way to solve this without giving up the entire functionality of the program?
We are working on a WPF application in .NET 4 that will be used with a touch screen. We are trying to use the built-in Windows OSK for our input, and the last remaining issue is to get the keyboard to open up as soon as a text box gets focus. Currently, if a text box gets focus, a small keyboard icon appears (this is the InputPanel icon) and the user has to tap that icon to make the keyboard open up.
Is there a way to skip the icon step, and just have the keyboard open up all the way on focus? Preferably something that can be set or coded in one place and apply to all text boxes globally? It also needs to use the current culture settings of the application thread (which it already appears to be doing).
I haven't been able to find anything in the control panel settings that lets you skip the icon step. I also found some examples online of using the TextInputPanel.CurrentInPlaceState, but when I implemented code to open up a TextInputPanel on preview focus of the main window, I kept getting COM INTEROP exceptions and basically hit a dead end (the Microsoft.Ink.dll is an interop DLL).
Is it possible that there is a registry key that can change the default CurrentInPlaceState to Expanded instead of HoverTarget? I haven't been able to find one in my net searching.
Thanks,
Valerie
EDIT: Here is some code that I put in the main window's code behind, as well as the exception message I keep getting - and I have no idea what it means or how to fix it (my net searches failed me!)
protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnPreviewGotKeyboardFocus(e);
TextBox textbox = e.NewFocus as TextBox;
TextBox oldTextbox = e.OldFocus as TextBox;
if (oldTextbox != null && boxesToInputs.ContainsKey(oldTextbox))
{
TextInputPanel oldPanel = boxesToInputs[oldTextbox];
oldPanel.Dispose();
boxesToInputs.Remove(oldTextbox);
}
if (textbox != null)
{
// Make sure we've cleaned up old panels, just in case
if (boxesToInputs.ContainsKey(textbox))
{
boxesToInputs[textbox].Dispose();
boxesToInputs.Remove(textbox);
}
TextInputPanel newPanel = new TextInputPanel(((HwndSource)PresentationSource.FromDependencyObject(textbox)).Handle);
newPanel.DefaultInPlaceState = InPlaceState.Expanded;
newPanel.DefaultInputArea = PanelInputArea.Keyboard;
boxesToInputs[textbox] = newPanel;
}
}
And here is the exception message, which occurs when my code calls the TextInputPanel constructor:
Retrieving the COM class factory for component with CLSID {F9B189D7-228B-4F2B-8650-B97F59E02C8C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
I verified that the platform target of the WPF app is x86. I ran Dependency Walker and it said that the Microsoft.Ink.dll I was using was 64 bit, and that two delay-loaded dependencies were missing (GPSVC.dll and IESHIMS.dll). I found a 32 bit version of Microsoft.Ink.dll, but I am still getting the same error, and Dependency Walker is saying the same thing - GPSVC.dll and IESHIMS.dll are missing.
I can't target x64, and I'd prefer not to have to put the missing DLLs into my application folder (if that would work?). I hope there is something simple I am missing, because this is a lot of trouble to just get rid of a keyboard hint...
Any help is greatly appreciated - I am a bit of a newb when it comes to working with unmanaged/interop assemblies...
I researched for a similar propose. In my case it was to create a custom OSK. It seems that (by now) it's not possible to create a custom input device. The explanation is in this link:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a813a08a-7960-45fe-bc91-e81cdb75bd10
Moreover, I found a "workaround" which uses Win32 API calls to access SendKey method, and report input independently of the target. The project that I found is:
http://wosk.codeplex.com/
SendKey is also available on WinForms (see http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx ) but I'm not sure if it will produce the same behavior.
I'll checking these options in the following days, but perhaps some of this information might help.
Regards
Herber
I am developing a WPF-application using mvvm pattern. And a strange problem occurred to me.
There is a form, which contains a devexpress DXGrid control. There is a command binded to double click gesture in presenter. When the command triggers a new window is created and shown through factory class(the Show() method is used).
So, it happens from time to time that the whole application(all application windows) is blocked when this window is shown. This lockup disappears after i focus any other application.
For the first time this problem occurred after updating devexpress version. Then this problem occurred any time new window was shown after double click on grid row. The problem was partially fixed by setting new window`s Owner property.
Now this problem occurs from time to time. It seems as if threads are involved here, but i dont understand how. =(
p.s.:
there is one more strange thing, when new window is shown and no lockup-problem occurred, the first window is still focused and i have to click on newly shown window before i can use any controls, placed on it.
I have tried:
set ShowActivated property
call Activate() after Show()
newform.Dispatcher.CheckAccess() to
determine which thread calls Show()
method
check newform.IsActive property after
show (value = true)
Could you tell me how to fix, please?
Thank you.
Well to fix the issue of first window being focused rather than the newly shown window, you need to do the following, after calling the show method for the new window:
Mouse.Capture(null);
Hopefully the issue would be resolved.
I have a problem with my Application ending unexpectedly when a modal dialog, spawned from the main program window, closes normally. No unhandled exceptions are being thrown and none of the Closing or Closed events are fired on the Main application window.
Essentially I have a main/shell window, which is started in the Application code using ShellWindow.Show(). Through a menu the user can spawn a custom open dialog, this is a new window created and then shown using ShowDialog (the windows owner is set to that of the shell window).
When the dialog is closed (internally, by a command invoking _modalDialogWindow.Close()) the application closes, whereas I would only have expected the modal dialog to have closed.
Debugging the code indicates that the ShellWindow is dumped from memory, as the next executed line of code after _modalDialogWindow.Close() is it falling out of Application.Run() in the static program code.
If anyone has any ideas I am willing to try anything.
It appears that, due to the MVVM/Ioc way I am designing the application window close events are being propagated further than they should. I don't understand this!
However, setting the Application.ShutDownMode to Explicit prevents the app from closing prematurely and I now have the desired behaviour.
Incidentally, turning on all the exceptions as suggested by declyclone didn't yield any exceptions that are thrown internally when then window is closed.
Don't create any windows before you create your application, or they won't get registered properly. They won't show up in Application.Current.Windows or Application.Current.MainWindow. Then when you create your dialog window, your application will think that it is both the MainWindow and the only window.
Example of what not to do:
public partial class App : Application, ISingleInstanceApp
{
MyWindow win = new MyWindow(); //BAD! this is called inside new App(), but before the actual App constructor.
[STAThread]
public static void Main()
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
var application = new App();
application.InitializeComponent();
application.Run();
// Allow single instance code to perform cleanup operations
SingleInstance<App>.Cleanup();
}
}
I had this problem too, your answer helped me figure out why.
I am using the SplashScreen feature in WPF by setting a bitmap's Build Action to Splashscreen. Behind the splash screen, licensing information is being check, and if it fails I show a MessageBox.
According to this Feedback, it is because the MessageBox.Owner is the splash screen and as soon as another window is open even if it is a MessageBox the splash screen window is closed which then in turn closes the MessageBox, so the user never sees the MessageBox.
So the workaround would be to set the MessageBox.Owner to another window, but that would mean that I have to instantiate another window which might not even be needed.
Would it be possible to set the MessageBox.Owner to the desktop window? And how, because the only other function that comes to mind is the GetDesktopWindow() api function, but that returns a window handle and MessageBox.Owner is a WPF Window.
Since using the desktop window as the parent for your modal dialogs is not a good idea, as #Nir pointed out in his answer, here are three other workarounds:
1) Use a hidden window. Create a tiny, non-modal window to act as the parent for your MessageBox or other modal dialog. This approach is described here:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/116bcd83-93bf-42f3-9bfe-da9e7de37546/
2) Create non-modal message windows. Change your startup mode to explicit shutdown and use a non-modal window to display your message. This approach is described in the answer to this StackOverflow question:
MessageBox with exception details immediately disappears if use splash screen in WPF 4.0
3) Call MessageBox twice. Apparently, the problem only affects the first modal dialog shown. So you could simply call your modal dialog twice, if you didn't mind the flash of the first one opening and closing.
https://connect.microsoft.com/VisualStudio/feedback/details/600197/wpf-splash-screen-dismisses-dialog-box
Personally, I don't like any of these workarounds. The only other option is to avoid the built-in SplashScreen functionality and to roll your own from scratch. Here's a link if you want to investigate that route further:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/8dd49fd0-9cc9-43c6-b285-6f119ab8a32e/
Finally, if you're as annoyed by this issue as I am, you can vote for Microsoft to fix this bug here:
http://connect.microsoft.com/VisualStudio/feedback/details/600197/wpf-splash-screen-dismisses-dialog-box
I came up with this solution myself, so maybe there's something wrong with it, but it seems to work perfectly:
Window temp = new Window() { Visibility=Visibility.Hidden };
temp.Show();
MessageBox.Show(temp, "An error occurred before the application could start.\n\nTechnical Details: " + ex.Message, "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Stop);
App.Current.Shutdown(1);
I found the problem. I am also using the build-in splash screen which causes this: WPF SplashScreen closes MessageBox
Can you post some code? I just tried adding this to the App.xaml.cs file in a new WPF application:
protected override void OnStartup(StartupEventArgs e)
{
if (MessageBox.Show("Start app?", "Confirm Start",
MessageBoxButton.YesNo) == MessageBoxResult.No)
{
this.Shutdown();
return;
}
this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);
base.OnStartup(e);
}
... and it works as expected (the "Confirm Start" prompt stays open until I've responded, and if I click "No" the app shuts down).
The desktop window is never the correct parent, read this to know why:
http://blogs.msdn.com/oldnewthing/archive/2004/02/24/79212.aspx
Now the problem described in this post doesn't happen so much because MS worked around it, in this post you can see how:
http://blogs.msdn.com/oldnewthing/archive/2006/11/02/931674.aspx
This issue is still an issue, I faced it recently. For me, the solution was to close immediately the splash screen in case of any issues:
SplashScreen splash = new(Assembly.GetAssembly(typeof(GuiApp))!, "Resources/img_my.png");
splash.Show(false);
using ServiceProvider? services = initializeApp();
if (services == null)
{
splash.Close(TimeSpan.Zero);
return -3;
}
After that MessageBox displayed normally.
this has helped me a lot .....
Given me new idea
but the example code that i have seen here has some modification required
here is an simple example in wpf with modification
now it is working
on button click
paste this code
if (System.Windows.Forms.MessageBox.Show("are u sure", "delete", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
this.Close();
}
else
{
MessageBox.Show("why not to delete");
}
This is not directly related to the OP's situation, but might be useful for others who are having problems with MessageBox being hidden behind other windows in certain special situations.
As #dthrasher mentions, one solution is to use a hidden dummy window. But sometimes even that is not enough. I had a situation where the solution was to not only use a hidden dummy window, but to turn on its TopMost property whenever I used it with MessageBox.
_formKludge.TopMost = true;
MessageBox.Show(_formKludge, "Nice informative message.", "Super-duper Program",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_formKludge.TopMost = false;