real problem:
Mainform read routine more than twice. and all components and objects inside of MainForm empty
Example:
button first run of excellent
add my code:
namespace CheckNet
{
/// <summary>
/// Description of MainForm.
/// </summary>
delegate void Function();
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
Btn_Inicio.Click += new EventHandler (Btn_InicioClick);
// VerificationForm += new EventHandler (VerificationForm);
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
private DPFP.Template Template;
private DPFP.Template myTemplate;
//
void Btn_InicioClick(object sender, EventArgs e)
{
// call rutine ejecutar boton primera vez
//
if (this.panelContenedor.Controls.Count > 0)
this.panelContenedor.Controls.RemoveAt(0);
VerificationForm hijos = new VerificationForm();
hijos.TopLevel = false;
hijos.FormBorderStyle = FormBorderStyle.None;
hijos.Dock = DockStyle.Fill;
this.panelContenedor.Controls.Add(hijos);
this.panelContenedor.Tag = hijos;
hijos.Show();
}
void Button7Click(object sender, EventArgs e)
{
AddFormInPanel(new Hijo2());
}
private void AddFormInPanel(object formHijo)
{
if (this.panelContenedor.Controls.Count > 0)
this.panelContenedor.Controls.RemoveAt(0);
Form fh = formHijo as Form;
fh.TopLevel = false;
fh.FormBorderStyle = FormBorderStyle.None;
fh.Dock = DockStyle.Fill;
this.panelContenedor.Controls.Add(fh);
this.panelContenedor.Tag = fh;
fh.Show();
}
void Close_bottonClick(object sender, EventArgs e)
{
Close();
}
}
}
////////// call Form VerificationForm
namespace CheckNet
{
/* NOTE: This form is inherited from the CaptureForm,
so the VisualStudio Form Designer may not load it properly
(at least until you build the project).
If you want to make changes in the form layout - do it in the base CaptureForm.
All changes in the CaptureForm will be reflected in all derived forms
(i.e. in the EnrollmentForm and in the VerificationForm)
*/
public class VerificationForm : CaptureForm
{
public void Verify(DPFP.Template template)
{
Template = template;
ShowDialog();
}
protected override void Init()
{
base.Init();
base.Text = "Fingerprint Verification ";
Verificator = new DPFP.Verification.Verification(); // Create a fingerprint template verificator
UpdateStatus(0);
}
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
template= TomarHuellaBd();
Template=template;
if (features != null)
{
// Compare the feature set with our template
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
Verificator.Verify(features, Template, ref result);
UpdateStatus(result.FARAchieved);
if (result.Verified)
{
MakeReport2(" ");
}
else
MakeReport("Huella no Identificado.");
}
}
private void UpdateStatus(int FAR)
{
// Show "False accept rate" value
SetStatus(String.Format("False Accept Rate (FAR) = {0}", FAR));
}
private DPFP.Template TomarHuellaBd()
{
// Verifica la Huella desde una base de Datos
bool Bandera=true;
try { // Validar Numero
int idEmpleado =int.Parse(Global_ip.Globalip.ToString());
} catch {
MessageBox.Show("Error Numero de Empleado ", Global_ip.Globalip.ToString());
Bandera=false;
//
return null;
//
}
try
{
int NumEmpleado=int.Parse(Global_ip.Globalip.ToString());
enlacedb db = new enlacedb();
FbConnection conexion2 = new FbConnection(db.connectionString);
conexion2.Open();
FbCommand Frda = new FbCommand("SELECT * FROM REGHUMAN WHERE ID_EMPLEADO=#ID_EMPLEADO", conexion2);
Frda.Parameters.Add("#ID_EMPLEADO",SqlDbType.VarChar).Value = NumEmpleado;
FbDataReader leerF = Frda.ExecuteReader();
bool fseek= leerF.Read();
if (fseek) {
Global_Nombre.GlobalNombre= leerF.GetValue(4).ToString();
Byte[] imageF = new Byte[Convert.ToInt32 ((leerF.GetBytes(2, 0,null, 0, Int32.MaxValue)))];
leerF.GetBytes(2, 0, imageF, 0, imageF.Length);
MemoryStream memfpt = new MemoryStream(imageF);
DPFP.Template template = new DPFP.Template(memfpt);
return template;
}
else
{
return null;
}
}
catch (Exception err2) {
MessageBox.Show(err2.ToString());
}
return null;
}
private DPFP.Template Template;
private DPFP.Template template;
private DPFP.Verification.Verification Verificator;
}
}
if the user requests running second time the same button
VerificationForm routines and residents are CaptureForm Digital Persona device and can not read the fingerprint
how to empty or reset the procedure or routine (MainForm, VerificationForm and CaptureForm)
Thank.
The Solution is:
modify the program.cs
private static void Main (string [] args)
{
Application.EnableVisualStyles ();
Application.SetCompatibleTextRenderingDefault (false);
Fm1 MainForm = new MainForm ();
Application.Run (fm1);
if (fm1.ToRestart)
Application.Restart ();
}
start
ToRestart public bool = false;
void Btn_InicioClick (object sender, EventArgs e)
{
ToRestart = true;
this.Close ();
}
to reset the fingerprint reader and winform controls
Thank
Related
I have a class that generates images in a thread and invokes an event on every frame. A Form subscribes to this event and displays the image in a PictureBox using Invoke.
If the image generation process is allowed to finish, all is good. However, if the Form is closed while the thread is running, the Form tries to stop the thread but ends up in some sort of a deadlock.
When I try to use the threaded class in without a Form or in a Console app, start the process, wait for a second, then Cancel it, everything works fine.
The question is, something must be wrong with either the Form_Closing method of the Form or the Stop method of the threaded class.
I have kept the code to a minimum and it can be pasted into LinqPad, etc.
An auxiliary question: Should the Process method invoke the Stop method to clean up?
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace VideoMask.WinFormsAppApp
{
internal static class Program
{
[STAThread]
private static void Main ()
{
Program.TestWithoutForm(); // Runs fine.
Program.TestWithForm(); // Deadlocks.
}
private static void TestWithForm ()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
private static void TestWithoutForm ()
{
new TestWithoutForm().Run();
}
}
public class TestWithoutForm
{
private VideoProcessor VideoProcessor = new VideoProcessor();
public TestWithoutForm ()
{
this.VideoProcessor.SourceFrameRead += this.VideoProcessor_SourceFrameRead;
}
public void Run ()
{
this.VideoProcessor.Start();
Thread.Sleep(1000);
this.VideoProcessor.Stop();
MessageBox.Show("Done");
}
private void VideoProcessor_SourceFrameRead (object sender, VideoProcessorEventArgs e)
{
var filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Sample.png");
e.Bitmap.Save(filename, ImageFormat.Png);
}
}
public class FormMain: Form
{
private PictureBox PictureBox = new PictureBox();
private VideoProcessor VideoProcessor = new VideoProcessor();
public FormMain ()
{
this.Controls.Add(this.PictureBox);
this.PictureBox.Dock = DockStyle.Fill;
this.Shown += this.FormMain_Shown;
this.FormClosing += this.FormMain_FormClosing;
this.WindowState = FormWindowState.Maximized;
}
private void FormMain_Shown (object sender, EventArgs e)
{
this.VideoProcessor.SourceFrameRead += this.VideoProcessor_SourceFrameRead;
this.VideoProcessor.Start();
}
private void FormMain_FormClosing (object sender, FormClosingEventArgs e)
{
this.VideoProcessor.Stop();
this.VideoProcessor.Dispose();
this.VideoProcessor = null;
}
private void VideoProcessor_SourceFrameRead (object sender, VideoProcessorEventArgs e)
{
this.Invoke
(
new Action
(
() =>
{
using (var bitmap = this.PictureBox.Image)
{
this.PictureBox.Image = new Bitmap(e.Bitmap);
}
}
)
);
}
}
public sealed class VideoProcessor: IDisposable
{
public event EventHandler<ErrorEventArgs> ConversionError = null;
public event EventHandler<VideoProcessorEventArgs> SourceFrameRead = null;
private Font Font = null;
private Bitmap Bitmap = null;
private Thread Thread = null;
private Graphics Graphics = null;
private readonly object SyncRoot = new object();
private CancellationTokenSource CancellationTokenSource = null;
public VideoProcessor ()
{
this.Bitmap = new Bitmap(800, 600, PixelFormat.Format32bppArgb);
this.Graphics = Graphics.FromImage(this.Bitmap);
this.Font = new Font(FontFamily.GenericSansSerif, 48, GraphicsUnit.Point);
}
public bool IsRunning { get; private set; }
public void Start ()
{
lock (this.SyncRoot)
{
if (this.IsRunning) { throw (new Exception("A video conversion process is already running.")); }
this.Stop();
this.CancellationTokenSource = new CancellationTokenSource();
this.Thread = new Thread(new ParameterizedThreadStart(this.Process));
this.Thread.Start(this.CancellationTokenSource);
}
}
public void Stop ()
{
lock (this.SyncRoot)
{
if (!this.IsRunning) { return; }
this.CancellationTokenSource?.Cancel();
this.Thread.Join();
this.Thread = null;
this.CancellationTokenSource?.Dispose();
this.CancellationTokenSource = null;
}
}
private void Process (object cancellationTokenSource)
{
var source = (CancellationTokenSource) cancellationTokenSource ?? throw (new ArgumentNullException(nameof(cancellationTokenSource)));
lock (this.SyncRoot) { if (this.IsRunning) { throw (new Exception("A conversion process is already running.")); } }
this.IsRunning = true;
for (var i = 1; i <= int.MaxValue; i++)
{
if (source.IsCancellationRequested) { break; }
this.Graphics.Clear(Color.White);
this.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, 10, 10);
this.SourceFrameRead?.Invoke(this, new VideoProcessorEventArgs(this.Bitmap));
Thread.Sleep(33);
}
this.IsRunning = false;
}
public void Dispose () => this.Stop();
}
public class VideoProcessorEventArgs: EventArgs
{
public Bitmap Bitmap { get; private set; }
public VideoProcessorEventArgs (Bitmap bitmap) { this.Bitmap = bitmap; }
}
}
In the overrided void onIncomingCall I open a new Background thread which shows a new (Popup) Form.
I try to pickup or decline the Call in this Form but then I get an System.AccessViolationException.
it seems that the current call object is locked and cannot be accessed from another Form.
If I use the currentcall.answer(prm) in the onIncomingCall void then the call is established successfully (without another Form and thread).
public class myaccount : Account
{
public override void onIncomingCall(OnIncomingCallParam prm)
{
Call call = new Call(this, prm.callId);
CallOpParam param = new CallOpParam();
param.statusCode = pjsip_status_code.PJSIP_SC_RINGING;
param.statusCode = pjsip_status_code.PJSIP_SC_OK;
pjsipfunctions.currentparam = param;
pjsipfunctions.currentcall = call;
var thread = new Thread(() =>
{
ShowPopup(call,prm.callId.ToString());
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
// Thread myCallingThread = new Thread(new ThreadStart(ShowPopup));
//myCallingThread.SetApartmentState(ApartmentState.STA);
//myCallingThread.IsBackground = true;
//myCallingThread.Start();
}
public void ShowPopup(Call myCall,string call_id)
{
IncommingCallPopup win = new IncommingCallPopup(ref myCall, call_id );
win.Show();
System.Windows.Threading.Dispatcher.Run();
}
}
#####################################
public IncommingCallPopup(ref Call info, string callid)
{
currentCall = info;
Callid = callid;
CurrentCall = currentCall;
Prm.statusCode = pjsip_status_code.PJSIP_SC_RINGING;
InitializeComponent();
labelCallId.Content = callid;
}
private void rejectcall(object sender, RoutedEventArgs e)
{
Prm.statusCode = pjsip_status_code.PJSIP_SC_DECLINE;
CurrentCall.hangup(Prm);
}
private void transfercall(object sender, RoutedEventArgs e)
{
}
private void takecall(object sender, RoutedEventArgs e)
{
Prm.statusCode = pjsip_status_code.PJSIP_SC_OK;
try
{
CurrentCall.answer(Prm);
}
catch(Exception ex)
{
}
}
After crazy searching and trying some things i've figured it out.
Every Thread must registered in the Endpoint that you can hangup, pickup or transfer your call in another Class(Window).
All you need is to write this Method in a Public class and call this void everytime you call your void from another window ->
public void callpopup(String number) {
checkThread();
//answer, decline or something else
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static void checkThread()
{
try
{
if (ep != null && !ep.libIsThreadRegistered())
ep.libRegisterThread(Thread.CurrentThread.Name);
}
catch (Exception e)
{
}
}
C# .net 3.5 Winforms application.
So here is the situation. I have a form that runs some code to that opens another forms in another thread. When that form opens, it performs certain tasks and then needs to close if those conditions are met. Problem is, it keeps throwing this exception and I have NO idea why.
]1)
Here are my snippets of code used in all this.:
Here is the function that opens the form in another thread: Program.cs
public static void new_downloader_thread()
{
Thread t = new Thread(new ThreadStart(open_downloader));
t.SetApartmentState(ApartmentState.STA);
if (Open_Downloader)
{
t.Start();
}
}
public static void open_downloader()
{
try
{
Application.Run(new DownloadInstall());
}
catch (Exception e)
{
MessageBox.Show(Convert.ToString(e));
}
}
Here is the code from the form that opens the form giving me the trouble: Manager.cs
private void new_System_Click(object sender, EventArgs e)
{
if (Program.Open_Downloader == false)
{
Program.Current_Download = "newsys.exe";
Program.Open_Downloader = true;
Program.new_downloader_thread();
}
else
{
download_busy();
}
}
Here is the form that is opening: DownloadInstall.cs
public partial class DownloadInstall : Form
{
/// Opening Declarations
private static System.Net.WebClient web_client;
private static System.Diagnostics.Stopwatch stop_watch;
private static bool downloading { get; set; }
private static bool is_name_update { get; set; }
private static int download_state { get; set; }
private static int elapsed { get; set; }
private static int opening { get; set; }
//private static int counter;
/// --------------------
public DownloadInstall()
{
InitializeComponent();
is_name_update = false;
downloading = false;
opening = 0;
web_client = new System.Net.WebClient();
web_client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Download_Progress);
web_client.DownloadFileCompleted += new AsyncCompletedEventHandler(Download_Complete);
stop_watch = new System.Diagnostics.Stopwatch();
/// Keypress event call and blanking out the box text.
this.name_update_field.Text = "";
this.name_update_field.KeyPress += new KeyPressEventHandler(no_period);
/// --------------------------------------------------
/// Changes the text to what file we are downloading.
this.file_name.Text = string.Format("Downloading {0}", Program.Current_Download);
/// -------------------------------------------------
/// Sets a forms closed event handler
this.FormClosing += new FormClosingEventHandler(Download_Window_Closing);
/// ---------------------------------
/// Creates folder where files are to be downloaded and deletes any residual files.
try
{
System.IO.Directory.CreateDirectory(#"C:\Downloads");
}
catch
{
}
if (System.IO.File.Exists(string.Format(#"C:\Downloads\{0}", Program.Current_Download)))
{
try
{
System.IO.File.Delete(string.Format(#"C:\Downloads\{0}", Program.Current_Download));
}
catch
{
if (Program.Disconnecting == false)
{
opening = 1;
}
}
}
/// -------------------------------------------------------------------------------
switch (opening)
{
/// Case 0 Starts the download or name update code normally.
case 0:
if (Program.Current_Download == "Name Update")
{
file_name.Text = "Name Update Downloader";
is_name_update = true;
this.restart_or_start.Text = "Start";
this.cid.Visible = true;
this.name_update_field.ReadOnly = false;
this.name_update_field.Visible = true;
}
else
{
Download_Begin();
}
break;
/// Case 1 will close the downloader.
case 1:
MessageBox.Show("It is possible this file was already downloaded and is already open on this computer.", "Hmmmmm...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.Close();
break;
}
}
/// Function that is called when the window is closed.
private void Download_Window_Closing(object sender, FormClosingEventArgs e)
{
if (downloading)
{
web_client.CancelAsync();
}
Program.Current_Download = "";
Program.Open_Downloader = false;
}
/// --------------------------------------------------
Not sure why this is throwing the exception. It seems if I remove code that closes the form, it works, and I can close the form properly from other parts of the code. Any help would be great!
Solved!!! The problem is when trying to close the form before it has finished construction.
Changed:
this.Close();
to:
Load += (s, e) => Close();
My word blocks add-ins for some reason. Following line gives no result.
ActiveDocument.Application.Selection.TypeText("Some String");
It appears as executed when debugging, however takes no effect on ActiveDocument. Do you know any possible reason? Macros/Add-ins are allowed in Word settings.
Michael
Basic word plug which store file into database before closing file.
public partial class ThisAddIn
{
private string friendlyErrorMessage = "An error has occurred inside the Case Manager Word Addin";
//static string filePath = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.DocumentBeforeClose += Application_DocumentBeforeClose;
}
//public static string dialogFilePath;
public static string dialogFileName;
public static Word.Document doc;
void Application_DocumentBeforeClose(Word.Document document, ref bool Cancel)
{
try
{
string filePath = this.Application.ActiveDocument.FullName.ToString();
string fileName = this.Application.ActiveDocument.Name;
//dialogFilePath = filePath;
dialogFileName = fileName;
doc = document;
string tempFile;
string tempPath;
//var form = new SaveFileDialog();
//form.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
//form.ShowDialog();
//System.Windows.Forms.MessageBox.Show(form.ToString());
//_T is for editing template and save file after saving.
//+ is for saving
//document.Save();
var iPersistFile = (IPersistFile)document;
iPersistFile.Save(tempPath, false);
if (filePath.Contains("_T"))
{
//Store file into DB
}
else
{
//Store file into DB
}
//object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
//document.Close(ref doNotSaveChanges, ref missing, ref missing);
Word._Document wDocument = Application.Documents[fileName] as Word._Document;
//wDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
ThisAddIn.doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
catch (Exception exception)
{
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
Create a Ribbon designer :
public partial class TestRibbon
{
private string friendlyErrorMessage = "An error has occurred inside the Case Manager Outlook Addin";
private void TestRibbon_Load(object sender, RibbonUIEventArgs e)
{
}
public TestRibbon()
: base(Globals.Factory.GetRibbonFactory())
{
InitializeComponent();
try
{
System.Data.DataTable dt = new DBCall().GetData();//Get all menu in word tmenu tab and bind them using following code
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
RibbonButton Field = this.Factory.CreateRibbonButton();
Field.Label = dt.Rows[i][1].ToString();
Field.Tag = i;
Field.ControlSize =
Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
Field.Click += Field_Click;
menu1.Items.Add(Field);
}
}
else
{
System.Windows.Forms.MessageBox.Show("No Fields are available in database");
}
}
catch (Exception exception)
{
}
}
/// <summary>
/// Ribbon Button Click Event
/// </summary>
void Field_Click(object sender, RibbonControlEventArgs e)
{
try
{
Microsoft.Office.Interop.Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;
currentRange.Text = (sender as RibbonButton).Label;
}
catch (Exception exception)
{
}
}
}
I've created a user control (windows form application) to get an instance of Word (either active or new), and provide a button to open documents into that instance using a file dialog picker.
The form contains 2 buttons, 1 for getting the word instance and another for opening a document. It also contains a list box for displaying the open documents, and an openfiledialog control to provide the means for selecting documents to open.
I am handling the Application.DocumentOpen event in order to populate the listbox...
m_wordApp.DocumentOpen += new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
I am determining when i need to reinvoke my method that populates the listbox to ensure that access to the control is on the same thread that created it....
private void AddDocument(string name)
{
try
{
if (m_documentsListBox.InvokeRequired && m_documentsListBox.IsHandleCreated&&!m_documentsListBox.IsDisposed)
{
this.Invoke(m_AddDocument, new object[] { name });
return;
}
if (!m_documentsListBox.Items.Contains(name))
m_documentsListBox.Items.Add(name);
}
catch (Exception ex)
{
}
}
Im not using 2 dots, and i believe i am releasing any COM objects correctly.
Why does the application hang on either the line of code that opens the document ...
WordDoc = m_wordDocs.Open(ref fileName);
or the line that reinvokes the AddDocument() method...
this.Invoke(m_AddDocument, new object[] { name });
somewhere along the line i think i must be having a thread issue, because the hang only happens if i choose to open a document using the button, rather than from within the Word application directly.
full code below...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
// use these for the core office & word references
using msoWord = Microsoft.Office.Interop.Word;
namespace MCDevNET.Office.Word.TestUIControls
{
public partial class OpenWordDocument : Form
{
public OpenWordDocument()
{
InitializeComponent();
m_openWordButton.Click += new EventHandler(buttonOpenWordApp_Click);
m_openDocumentButton.Click += new EventHandler(buttonOpenDocument_Click);
m_AddDocument = new UpdateListControl(AddDocument);
}
#region Form: control eventHandlers
void buttonOpenWordApp_Click(object sender, EventArgs e)
{
try
{
if (!IsValid(m_wordApp))
WordApp = GetInstance();
AddAllDocuments();
}
catch (Exception ex)
{
}
}
void buttonOpenDocument_Click(object sender, EventArgs e)
{
OpenWordDoc();
}
public delegate void UpdateListControl(string name);
private UpdateListControl m_AddDocument;
private void AddDocument(string name)
{
try
{
if (m_documentsListBox.InvokeRequired && m_documentsListBox.IsHandleCreated&&!m_documentsListBox.IsDisposed)
{
this.Invoke(m_AddDocument, new object[] { name });
return;
}
if (!m_documentsListBox.Items.Contains(name))
m_documentsListBox.Items.Add(name);
}
catch (Exception ex)
{
}
}
private void AddAllDocuments()
{
try
{
m_documentsListBox.Items.Clear();
if (m_wordDocs != null)
{
for (int i = 1; i <= m_wordDocs.Count; i++)
AddDocument(m_wordDocs[i].Name);
}
}
catch (Exception ex)
{
}
}
#endregion
#region Word: properties & eventhandlers
private msoWord.Document m_wordDoc;
public msoWord.Document WordDoc
{
get { return m_wordDoc; }
private set
{
try
{
if (m_wordDoc != value)
{
ReleaseCOMObject(m_wordDoc);
m_wordDoc = value;
}
}
catch (Exception ex)
{
}
}
}
private msoWord.Documents m_wordDocs;
public msoWord.Documents WordDocs
{
get { return m_wordDocs; }
private set
{
try
{
if (m_wordDocs != value)
{
ReleaseCOMObject(m_wordDocs);
m_wordDocs = value;
}
}
catch (Exception ex)
{
}
}
}
private msoWord.Application m_wordApp;
public msoWord.Application WordApp
{
get { return m_wordApp; }
set
{
try
{
if (m_wordApp != value)
{
if (m_wordApp != null)
{
m_wordApp.DocumentOpen -= new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
ReleaseCOMObject(m_wordApp);
}
m_wordApp = value;
if (IsValid(m_wordApp))
{
m_wordApp.DocumentOpen += new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
WordDocs = m_wordApp.Documents;
}
}
}
catch (Exception ex)
{
}
}
}
void m_wordApp_DocumentOpen(msoWord.Document doc)
{
try
{
string name = doc.Name;
AddDocument(name);
}
catch (Exception ex)
{
}
finally
{
ReleaseCOMObject(doc);
doc = null;
}
}
private msoWord.Application GetInstance()
{
msoWord.Application app = null;
try
{
app = (msoWord.Application)Marshal.GetActiveObject("Word.Application");
}
catch (Exception ex)
{
if (app == null)
app = new msoWord.Application();
}
finally
{
if (IsValid(app))
{
app.Visible = true;
app.Activate();
}
}
return app;
}
private void OpenWordDoc()
{
try
{
m_openFileDialog.AddExtension = true;
m_openFileDialog.Filter = "All Word (*.docx; *.docm; *.doc; *.dotx; *.dotm; *.dot)|*.docx;*.docm;*.doc;*.dotx;*.dotm;*.dot|Word Documents (*.docx)|*.docx|Word Macro-Enabled Documents (*.docm)|*.docm|Word 97-2003 Documents (*.doc)|*.doc|All Word Templates (*.dotx; *.dotm; *.dot)|*.dotx;*.dotm;*.dot|Word Templates (*.dotx)|*.dotx|Word Macro-Enabled Templates (*.dotm)|*.dotm)";
m_openFileDialog.FilterIndex = 1;
m_openFileDialog.Multiselect = false;
m_openFileDialog.Title = "Open Word Document";
if (m_openFileDialog.ShowDialog() == DialogResult.OK)
{
object fileName = m_openFileDialog.FileName;
WordDoc = m_wordDocs.Open(ref fileName);
}
}
catch (Exception ex)
{
}
}
private bool IsValid(msoWord.Application app)
{
try
{
if (app != null)
{
string name = app.Caption;
return true;
}
}
catch (Exception ex)
{
}
return false;
}
#endregion
private void ReleaseCOMObject(object comObject)
{
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
if (comObject != null && Marshal.IsComObject(comObject))
Marshal.ReleaseComObject(comObject);
}
catch (Exception ex)
{
}
}
}
}
namespace MCDevNET.Office.Word.TestUIControls
{
partial class OpenWordDocument
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.m_documentsListBox = new System.Windows.Forms.ListBox();
this.m_openDocumentButton = new System.Windows.Forms.Button();
this.m_openWordButton = new System.Windows.Forms.Button();
this.m_openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// lb_Documents
//
this.m_documentsListBox.FormattingEnabled = true;
this.m_documentsListBox.Location = new System.Drawing.Point(12, 41);
this.m_documentsListBox.Name = "lb_Documents";
this.m_documentsListBox.Size = new System.Drawing.Size(156, 134);
this.m_documentsListBox.TabIndex = 8;
//
// m_openDocumentButton
//
this.m_openDocumentButton.Location = new System.Drawing.Point(93, 12);
this.m_openDocumentButton.Name = "m_openDocumentButton";
this.m_openDocumentButton.Size = new System.Drawing.Size(75, 23);
this.m_openDocumentButton.TabIndex = 7;
this.m_openDocumentButton.Text = "Doc";
this.m_openDocumentButton.UseVisualStyleBackColor = true;
//
// m_openWordButton
//
this.m_openWordButton.Location = new System.Drawing.Point(12, 12);
this.m_openWordButton.Name = "m_openWordButton";
this.m_openWordButton.Size = new System.Drawing.Size(75, 23);
this.m_openWordButton.TabIndex = 6;
this.m_openWordButton.Text = "Word";
this.m_openWordButton.UseVisualStyleBackColor = true;
//
// m_openFileDialog
//
this.m_openFileDialog.FileName = "openFileDialog1";
//
// OpenWordDocument
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(182, 184);
this.Controls.Add(this.m_documentsListBox);
this.Controls.Add(this.m_openDocumentButton);
this.Controls.Add(this.m_openWordButton);
this.Name = "OpenWordDocument";
this.Text = "OpenWordDocument";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox m_documentsListBox;
private System.Windows.Forms.Button m_openDocumentButton;
private System.Windows.Forms.Button m_openWordButton;
private System.Windows.Forms.OpenFileDialog m_openFileDialog;
}
}
The hang happens on the call to Documents.Open(fileName)
You have an event handler wired up for the Application.DocumentOpen event. On removing this event handler the hang no longer occurs.
I presume the reason for the problem is that you are getting deadlocked as Word tries to fire that event before the Documents.Open call returns. Meaning the thread that handles the event is still busy.
Replacing
WordDoc = m_wordDocs.Open(ref fileName)
with
new System.Threading.Tasks.Task(() => WordDoc = m_wordDocs.Open(ref fileName))
.Start();
To open the document on a different thread seems to resolve the issue.