WindowInteropHelper.Handle — do I need to release it? - wpf

In WPF I'm getting IntPtr handle using this code:
IntPtr mainWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle
When I finish using this handle, do I need to release it in anyway (e.g. using Marshal.FreeHGlobal() method) ?
EDIT: I was thinking about Marshal.FreeHGlobal(), not Marshal.Release(), sorry!

This is not in any way related to COM, Marshal.Release() does not apply. You simply get a copy of the native window handle, it does not have to be released. You need to stop using the handle when the window is destroyed. Signaled by the Window.Close event.

Related

Get currentDevice Context in DX9.0c

I have a framework (so I don't inject anything to a running process) that uses DX9.0c and WinApi to create a Window and initialize DirectX. However, I do not have either device context nor HWND. Is there any way to obtain device context in this situation? Or should I try to create dummy HWND and create a new device context?
Use NULL as a parameter for CreateCompatibleDC to get an device context which is compatible to your screen.
HDC hdcDC = ::CreateCompatibleDC( NULL );
See https://msdn.microsoft.com/en-us/library/windows/desktop/dd183489(v=vs.85).aspx for more details.

Question about making Asynchronous call in C# (WPF) to COM object

Sorry to ask such a basic question but I seem to have a brain freeze on this one! I'm calling a COM (ATL) object from my WPF project. The COM method might take a long time to complete. I thought I'd try and call it asychronously. I have a few demo lines that show the problem.
private void checkBox1_Checked(object sender, RoutedEventArgs e)
{
//DoSomeWork();
AsyncDoWork caller = new AsyncDoWork(DoSomeWork);
IAsyncResult result = caller.BeginInvoke(null, null);
}
private delegate void AsyncDoWork();
private void DoSomeWork()
{
_Server.DoWork();
}
The ATL method DoWork is very exciting. It is:
STDMETHODIMP CSimpleObject::DoWork(void)
{
Sleep(5000);
return S_OK;
}
I had expectations that running this way would result in the checkbox being checked right away (instead of in 5 seconds) and me being able to move the WPF gui around the screen. I can't - for 5 seconds.
What am I doing wrong? I'm sure it's something pretty simple. Delegate signature wrong?
Thanks.
I'm sure you're right about the call to your ATL code getting marshaled to the GUI thread because the ATL code is STA, thereby blocking your GUI thread.
Two solutions:
Rearchitect the ATL portion to be MTA, which may not be feasible, or
Leave the ATL as STA but initially construct the COM object in a thread created for that purpose so it will get a different apartment.
A WPF application actually runs just fine with multiple UI threads, as long as each UI thread has manages its own part of the UI, and the parts are separated by HwndSource. In other words, the second thread that runs part of the UI implements a Win32 HWND which is then embedded in the portion of the UI run by the main thread.
If your COM object isn't itself a GUI object, then it should be very easy to construct it in a separate worker thread and leave it there. Since it is a STA object, all calls will be marshaled to the other thread.
BeginInvoke is still going to execute your call on the same thread, just asynchronously*. You can either create a new Thread object:
Thread comthread = new Thread(new ThreadStart(delegate() { DoSomeWork(); }));
comthread.Start();
or try out .Net 4's new Task library:
Task.Factory.StartNew(() =>
{
DoSomeWork();
});
which are essentially the same thing.**
*A delegate type's BeginInvoke method executes on the same thread as the caller, but in the background. I'm not sure if there are rules regarding what gets executed when, but it's certainly not in the order you want. However, asynchronous methods like BeginRead execute on a special thread separate from the main one.
**There is a slight difference - the Thread method will always create a new Thread object, whereas the Task system has a pool of threads to work with, which is in theory more efficient.
I have done some more thinking and testing about this. There is nothing wrong with the C# code. If the ATL object is an STA object (as it was in my case), it will be called on the main thread, regardless of attempts by the C# code to call it on a worker thread. Changing the ATL object to an MTA object makes it possible to to call it asynchronously.

"The calling thread must be STA, because many UI components require this." Error in WPF?

I am creating a xps document as below.
Assembly assembly = Assembly.GetExecutingAssembly();
//read embedded xpsDocument file
Stream helpStream = assembly.GetManifestResourceStream(resourceNameOfContext);
if (helpStream != null)
{
Package package = Package.Open(helpStream);
string inMemoryPackageName = "memorystream://" + topicName + ".xps";
Uri packageUri = new Uri(inMemoryPackageName);
//Add package to PackageStore
PackageStore.AddPackage(packageUri, package);
docXps = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);
}
return docXps;
When i am trying to get docXps.GetFixedDocumentSequence();
I am getting the above error. Can anyone help?
Thanks,
Your problem has nothing to do with the code surrounding the creation or use of the XPS document. It has everything to do with what thread you are running under.
You will receive the The calling thread must be STA, because many UI components require this error whenever any of the following are attempted on a MTA thread:
You construct any object derived from FrameworkElement (including Controls and Panels)
You construct any object derived from BitmapEffect
You construct any object derived from TextComposition
You construct any object derived from HwndSource
You access the current InputManager
You access the primary KeyboardDevice, StylusDevice, or TabletDevice
You attempt to change the focus on a FrameworkContentElement
You provide mouse, keyboard or IME input to any control that accepts text input
You make WPF content visible or update its layout
You manipulate the visual tree in such a way as to cause a re-evaluation for rendering
Several other changes, mostly having to do with display and input
For example, I received this error last year when I tried to deserialize some XAML that contained <Button> and other WPF objects from within a WCF service. The problem was simple to solve: I just switch to a STA thread to do the processing.
Obviously most work with XPS documents will trigger one or more of the above conditions. In your case I suspect that GetFixedDocumentSequence ends up using TextComposition or one of its subclasses.
No doubt the my solution of switching to a STA thread will also work for you, but first you need to figure out how your code that works with XpsDocuments is getting executed run from a MTA thread. Normally any code from from the GUI (eg a button press) is automatically run in a STA thread.
Is it possible that your code that manipulates XPS Documents may be being executed without a GUI? From a user-created thread? From a WCF service or a web service? From an ASPX page? Track that down and you'll probably find your solution.
If that doesn't work, let us know the details of the path through which GetFixedDocumentSequence is called, so we can diagnose it. The directly surrounding code isn't nearly as important as the call stack and how it is originally being invoked. If it is hard to explain you probably should add a call stack to prevent misunderstandings and help us diagnose the problem further, or tell you how to start a STA thread in your particular situation.
Is your code trying to access the xps doc from a background thread? If this is the case, you'll want to use the dispatcher. Info on that here.
If this doesn't help, could you post the code where you're actually calling GetFixedDocumentSequence()?

Generic GDI+ Error

I have a Form being launched from another form on a different thread. Most of the time it works perfectly, but I get the below error from time to time. Can anyone help?
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at System.Drawing.Icon.ToBitmap()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
The user has to be able to see multiple open accounts simultaneously, right? So you need multiple instances of a form?
Unless I'm misreading something, I don't think you need threads for this scenario, and I think you are just introducing yourself to a world of hurt (like these exceptions) as a result.
Assuming your account form is called AccountForm, I'd do this instead:
Dim acctForm As New AccountForm()
acctForm.Show()
(Of course you'll have your own logic for that ... ) I might even put it in the ShowForm method so that I could just update my caller thusly:
ShowForm()
And be done. Now all of this assumes that you've encapsulated the AccountForm nicely so that each instance has its own data, and they don't share anything between instances.
Using threads for this is not only overkill, but likely to introduce bugs like the exception at the top. And my experience in debugging multi-threaded WinForms apps has shown that these bugs are often very difficult to replicate, and extremely tricky to find and fix. Oftentimes, the best fix is to not multithread unless you absolutely, positively have to.
Can you elaborate what you are trying to do here?
If you are trying to show a Form from a different thread than the UI thread then refer to this question:
My form doesn't properly display when it is launched from another thread
The application is an Explorer-Type customer management system. An account form is launched from the "Main" explorer form on a separate background thread. We do this because the user needs to be able to have multiple accounts open at the same time.
We launch the form using this code:
Thread = New Thread(AddressOf ShowForm)
Thread.SetApartmentState(ApartmentState.STA)
Thread.IsBackground = True

Launching IE from winforms, can I close IE when my winforms closes?

I have a winforms application, that why someone clicks on a button I need to open up IE to a specific URL.
When someone closes the winforms app, I then need to close IE.
Is this possible? If yes, how?
If you dont have the reference to the old process you used for launching IE, you have to search through the process array returned by System.Diagnostics.Process.GetProcessesByName("IEXPLORE") and kill the specific process.
some samples here.
It would be possible to do that, but it might be a better idea to simply embed Internet Explorer into your application using the WebBrowser control. That way when you close the website you have no chance of closing the whole window when your website opened in a new tab in an existing IE window.
Edit: If you're going to do it anyway, look at the MSDN page on System.Diagnostics.Process.Close
Yes it is possible,
When you call System.Diagnostics.Process.Start() to start the browser, use a specifically created process object. You can later use the process information to kill the process.
However, as Dan Walker mentioned, it might be a better idea to just use the Web Browser control, unless you have specific navigation needs, then it might be more effective to just start and kill IE.
Not sure how you are launching IE, but if you keep a reference to the launched process (or the window handle that was created), you can kill the process (or close the window) when you app exits.
EDIT:
Code to close a window handle is like
Utilities.Utilities.SendMessage(mTestPanelHandle, WM_COMMAND, WM_CLOSE, 0);
if you have a P/Invoke
public const int WM_COMMAND = 0x0112;
public const int WM_CLOSE = 0xF060;
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int SendMessage(IntPtr hwnd, uint Msg, int wParam, int lParam)
Try this (assuming by WinForms you are using .NET)
Process ieProcess = Process.Start("iexplore", #"http://www.website.com");
// Do work, etc
ieProcess.Kill();
This will only kill the instance you started.

Resources