Opening AutoCAD drawing inside a Windows Form in C# - c#

I have the following function which opens a dxf file in an Autocad Exe, by zooming a specific coordinate via my C# desktop application.
public static void zoomDrwaing(String drawingFile, String lotId)
{
AcadApplication acadApp = null;
AcadDocument doc = null;
double[] coordinates = new double[3];
String errorMessage = "";
try
{
coordinates = ReadCoordinates(drawingFile, lotId); // done via netDxf api
acadApp = new Autodesk.AutoCAD.Interop.AcadApplication();
acadApp.Visible = true;
doc = acadApp.Documents.Open(drawingFile, true);
double[] points = new double[3] { coordinates[0], coordinates[1], coordinates[2] };
acadApp.ZoomCenter(points, 30);
}
catch (Exception ex)
{
errorMessage = ex.ToString();
}
finally
{
if (acadApp != null) Marshal.FinalReleaseComObject(acadApp);
}
}
I would like to know whether there is any possibility of loading the Autocad Exe (with the zoomed dxf file) inside one of the Windows forms in my desktop application it-self rather than opening the exe separately.

I haven't tried it but apparently you can use the ActiveX control from DWG Trueview Here is a forum post on the Autodesk forum with some sample code. Googling DWG Trueview Activex should generate some reading material. Or you may just read this and abandon all hope. The $$ alternative is RealDwg or Open Design. Read the AutoCAD Tag wiki for more resources and info on that.
Because Autodesk love to destroy their inbound links from time to time, you should be able to land on the first topic I mentioned using Google if they kill it again. Don't get me started on that.

Related

How to access AutoCad elements / get xyz coordinates from Autocad

I'm looking for a way to access a linked Autocad File using the Revit API. I have SnoopDB already installed which is a huge help.
I found this which was also another step forward however I'm not able to get the points or lines of the file.
I've explored a bit and have found that I am able to access the filename and then get the hashcode of the cadlink but after that, idk how to get the goemetry within.
Any and all help is appreciated.
here is what I have so far:
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Selection sel = uidoc.Selection;
using (Transaction tx = new Transaction(doc))
{
try
{
tx.Start("Tracing Cad");
Reference refer = sel.PickObject(ObjectType.Element, "Select a CAD Link");
Element elem = doc.GetElement(refer);
GeometryElement geoElem = elem.get_Geometry(new Options());
Debug.WriteLine("elem.Category.Name: " + elem.Category.Name); // can grab title of CAD
foreach (GeometryObject geoObj in geoElem)
{
GeometryInstance instance = geoObj as GeometryInstance;
foreach (GeometryObject instObj in instance.SymbolGeometry)
{
Debug.WriteLine("geoObj.GraphicsStyleId: " + geoObj.GraphicsStyleId);
Debug.WriteLine("geoObj.GetHashCode(): " + geoObj.GetHashCode()); // gets hashcode of selected cad link
if (instObj.GetType().Name == "PolyLine")
// if (instObj.GetType().Name == "GeometryInstance")
{
}
else
{
Debug.WriteLine("there are no blocks found in this CAD File");
}
}
}
tx.Commit();
} catch (Exception e )
{
Debug.WriteLine(e.StackTrace);
}
The Revit API does not provide any access to the internals of a linked CAD file.
All you can do is implement some AutoCAD.NET code to read the DWG file itself, provided you have access to the DWG and AutoCAD is installed.
The Building Coder shares some samples showing how to launch AutoCAD within a Revit add-in.

Microsoft word automation

We have an UWP application and we would like to have the following scenario:
open Microsoft word from it with a document
edit document
close document and get data to our application.
We have an Silverlight application that uses the code below and resolves the problem nicely. Can we do something similar in UWP? Programmatically open Word and wait for instance closing.
private void SetupWordInstance(bool visible = true)
{
if (AutomationFactory.IsAvailable)
{
_wordApp = null;
try
{
_wordApp = AutomationFactory.CreateObject("Word.Application");
_wordVersion = _wordApp.Version;
}
catch
{
try
{
_wordApp = AutomationFactory.CreateObject("Word.Application");
_wordVersion = _wordApp.Version;
}
catch (Exception)
{
Utils.ShowMessage(Resource.MissingWordApplicationErrorMessage);
}
}
if (_wordApp != null)
{
AutomationEvent beforeCloseEvent = AutomationFactory.GetEvent(_wordApp, "DocumentBeforeClose");
beforeCloseEvent.AddEventHandler(new BeforeCloseAppDelegate(BeforeCloseApp));
AutomationEvent quitEvent = AutomationFactory.GetEvent(_wordApp, "Quit");
quitEvent.AddEventHandler(new QuitAppDelegate(QuitApp));
if (visible)
{
_wordApp.Visible = true;
_wordApp.Activate();
FocusWordInstance();
}
}
}
else
{
Utils.ShowMessage(Resource.MissingAutomationErrorMessage);
}
}
There is a possibility that it can correspond by the technology called desktop bridge which Microsoft provides. Here's an explanation. Easily, it is to extract the Windows Desktop function not available in UWP and provide it together with application.
Docs/Windows/UWP/Develop/Porting apps to Windows 10/Desktop Bridge
The following is a sample when using Excel.
Desktop app bridge to UWP Samples
UWP calling Office Interop APIs
Windows Application Packaging Project Samples
Excel.Interop
Since the definition of Word API is below, it seems that it can be used as above.
Microsoft.​Office.​Interop.​Word Namespace

How to launch a process which will open a text file in any editor and automatically move cursor to a certain line number?

From c#, I want to launch a process which will open a text file in any editor and automatically move cursor to a certain line number.
I can open a file using
Process.Start(#"c:\myfile.txt");
but I don't know how to move cursor at specific location in that file.
Answer with source code:
yes, I used notepad++
private void openLog() {
try {
// see if notepad++ is installed on user's machine
var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
if (nppDir != null) {
var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
var nppReadmePath = Path.Combine(yourDirectory,fileName );
var line = 20;
var sb = new StringBuilder();
sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, lineNo);
Process.Start(nppExePath, sb.ToString());
} else {
string newPath = #"\\mySharedDrive\notpad++\bin\notepad++.exe";
Process.Start(newPath, #"\\" + filePath + " -n" + lineNo); // take exe from my shared drive
}
} catch (Exception e) {
Process.Start(#"\\" + FilePath); // open using notepad
}
}
Get Notepad++, then you can do this:
var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
var nppReadmePath = Path.Combine(nppDir, "readme.txt");
var line = 20;
var sb = new StringBuilder();
sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, line);
Process.Start(nppExePath, sb.ToString());
In this example we get install path of n++ from the registry, build path to exe and readme.txt file, opens its own readme.txt file with cursor on line 20.
Using StringBuilder is more efficient than using multiple appends (explanation somewhere on SO).
The solution very heavily depends on which process/editor is opened on your system. That editor would have to have a developer API that you could use to access functionality such as setting ranges and altering the cursor position. For example, if the editor that is opened is Microsoft Word, you would use the Word Interop API to set a selection at a specific position. There is no universal way to do this in 'any editor' since each one has its own API (or no outward facing API at all).
Perhaps you are going this the wrong way. I'm not sure what you are trying to accomplish, but I think it would be alot easier to just open the text file in an editor that belongs to your application. Perhaps another form with a WYSIWYG editor control. That way you have full control on where the cursor will land in that editor. Otherwise, there are just way too many unknowns for anything feasibly workable.

Can't open a mpg-File for capture using EmguCV with C#

I'm trying to open a mpg-File using emguCV. I use the following code:
if (instance == null)
{
lock (m_lock)
{
try
{
instance = new Capture(0); // capture from camera works fine if a camera is connected
}
catch (NullReferenceException)
{
String sFileName = #"C:\tmp\MarkerMovie.mpg";
try
{
if (File.Exists(sFileName))
{
instance = new Capture(sFileName); // here the exception is thrown
}
else
{
MessageBox.Show("No Camera and no Video-File found");
}
}
catch (NullReferenceException)
{
MessageBox.Show("Couldn't open Video: "+sFileName);
}
}
}
}
If a webcam is connected everything works fine, but when I unplug the webcam the line instance = new Capture(sFileName); throws a NullReferenceException:
Message = "Unable to create capture from C:\tmp\MarkerMovie.mpg"
I debugged and found the reason is in the constructor of capture. The following command always returns a Null-Pointer:
_ptr = CvInvoke.cvCreateFileCapture(fileName);
I could open the same video using C++ using this code:
cap = cvCaptureFromFile("C:\\tmp\\MarkerMovie.mpg");
I'm new to openCV, so I'm not sure which information you need to help me. I installed emguCV yesterday from http://sourceforge.net/projects/emgucv/ on a Windows XP computer. The installer-version is x86_2.3.0.1416. I included opencv_core231.dll, opencv_highgui231.dll and opencv_imgproc231.dll to my project.
Does somebody know how I can make this code working?
Let me know if you need more information.
Thanks.
I had the same problem and adding the opencv_ffmpeg.dll to the project seems to solve it. (Found in the bin directory in the Emgu CV directory) I have tried it on the project that you posted and it seems to be working too. Hope it helps.
With EmguCV in C#, you need to put the opencv_ffmpeg.dll, for example: opencv_ffmpeg2410.dll, be careful if you have x86 or 64 bits

C# SAPI in a web service

var speechEngine = new SpVoiceClass();
SetVoice(speechEngine, job.Voice);
var fileMode = SpeechStreamFileMode.SSFMCreateForWrite;
var fileStream = new SpFileStream();
try
{
fileStream.Open(filePath, fileMode, false);
speechEngine.AudioOutputStream = fileStream;
speechEngine.Speak(job.Script, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak | SpeechVoiceSpeakFlags.SVSFDefault); //TODO: Change to XML
//Wait for 15 minutes only
speechEngine.WaitUntilDone((uint)new TimeSpan(0, 15, 0).TotalMilliseconds);
}
finally
{
fileStream.Close();
}
This exact code works in a WinForm app, but when I run it inside a webservice I get the following
System.Runtime.InteropServices.COMException was unhandled
Message="Exception from HRESULT: 0x80045003"
Source="Interop.SpeechLib"
ErrorCode=-2147201021
Does anyone have any ideas what might be causing this error? The error code means
SPERR_UNSUPPORTED_FORMAT
For completeness here is the SetVoice method
void SetVoice(SpVoiceClass speechEngine, string voiceName)
{
var voices = speechEngine.GetVoices(null, null);
for (int index = 0; index < voices.Count; index++)
{
var currentToken = (SpObjectToken)voices.Item(index);
if (currentToken.GetDescription(0) == voiceName)
{
speechEngine.SetVoice((ISpObjectToken)currentToken);
return;
}
}
throw new Exception("Voice not found: " + voiceName);
}
I have given full access to USERS on the folder C:\Temp where the file is to be written. Any help would be appreciated!
I don't think the System.Speech works in windows service. It looks like there is a dependency to Shell, which isn't available to services. Try interop with SAPI's C++ interfaces. Some class in System.Runtime.InteropServices may help on that.
Our naming convention requires us to use a non-standard file extension. This works fine in a Winforms app, but failed on our web server. Changing the file extension back to .wav solved this error for us.
Make sure you explicitly set the format on the SPFileStream object. ISpAudio::SetState (which gets called in a lower layer from speechEngine.Speak) will return SPERR_UNSUPPORTED_FORMAT if the format isn't supported.
I just got the webservice to spawn a console app to do the processing. PITA :-)

Categories

Resources