Author Topic: Lauching Autocad from a VB exe? No luck...  (Read 18097 times)

0 Members and 1 Guest are viewing this topic.

havano

  • Guest
Lauching Autocad from a VB exe? No luck...
« on: April 25, 2006, 09:31:20 PM »
Hi all,

Although being a novice at VB(A), I really enjoy using it (most of the time)!

At the moment I'm developing an Autocad application for a customer. For various reasons (ease of use, anti-piracy) I would eventually like to convert the VBA macro to an executable. To that effect I mailed the customer a small test program, compiled with VB6, which essentially consisted of the following:
Code: [Select]
Public AcadObj As AcadApplication
Set AcadObj = CreateObject("AutoCAD.Application")
AcadObj.Visible = True
It worked fine on my system. However, after mailing it to the customer, he reported back the following error message:
Run-time error '429' ActiveX component can't create object

So I mailed him the next version of the test program, its code derived from Joe Sutphin's Autocad 2006 VBA book:
Code: [Select]
Public AcadObj As AcadApplication
Set AcadObj = CreateObject(Class:="AutoCAD.Application")
AcadObj.Visible = True
Now the customer reported another error message:
Run-time error '13' Type mismatch

He also mentioned that there were multiple versions of Autocad on his system: R14, 2006LT and 2006 full version. Don't ask why. So I looked here and elsewhere for a solution and found the following:
Code: [Select]
Public AcadObj As AcadApplication
Set AcadObj = CreateObject("AutoCAD.Application.16.2")
AcadObj.Visible = True
The "16.2" addition should make sure to launch Autocad 2006 full version. However, this attempt put us right back in square 1:
Run-time error '429' ActiveX component can't create object

Meanwhile, in order to verify that the code should work on other systems, I rigged up an ancient PC of mine (PII 300MHz, 128MB memory) with a clean install of XP Home and Autocad 2006 full version. All three versions of my test program launched Autocad flawlessly!

Any ideas why my customer's test-runs keep returning errors, anyone?
« Last Edit: April 25, 2006, 10:44:50 PM by havano »

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16897
  • Superior Stupidity at its best
Re: Lauching Autocad from a VB exe? No luck...
« Reply #1 on: April 25, 2006, 10:34:40 PM »
This may be an issue attempting a late binding when you have already bound the type library at design time.

Try this:
Code: [Select]
Function GetAcadObject(Optional ByVal AcadVersion As Variant) As Object
 On Error Resume Next
 Set GetAcadObject = GetObject(, "AutoCAD.Application" & AcadVersion)
    If Err <> 0 Then
        Err.Clear
        Set GetAcadObject = CreateObject("AutoCAD.Application" & AcadVersion)
        If Err <> 0 Then
            MsgBox "Could not load or find AutoCAD.", vbExclamation
            End
        End If
    End If
End Function

Now make sure you remove ALL references to the AutoCAD type library when you are done writing your code,  also, whenever you are in need of including an AutoCAD entity as an object in the program, make sure you reference it as an "Object" rather than AcadApplication or AcadLWPolyline or anything Acadxxxxxxx as it will cause issues if the type ibrary required is different than the design time type library.

You also will need to maintain a valid reference to the AcadObject created (or referenced) in order to make the program function properly. For example: If you set AC to the AutoCAD application object, you will need to use AC.property or AC.method rather than simply referencing themethod or property directly.

If you require a specific version of AutoCAD to work with your program, you can call it like so:

Code: [Select]
Set AC = GetAcadObject(".15")

For version independent referencing
Code: [Select]
Set AC = GetAcadObject()
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #2 on: April 25, 2006, 11:42:05 PM »
Thanks for your speedy reply, Keith!

Your first lines left me somewhat puzzled (being a novice) but I suppose they mean that I'd better not compile my VB code referencing an Autocad type library differing from the one in use by my customer.
OK, I'll keep that in mind. Although I suppose that since the application will be built and  used with Autocad 2006 (by customer's special request) those libraries are identical.

The code snippet you include in your post is very similar to the code in the first version of my test program, except that I skipped the GetObject bit and the inherent error trapping.

Indeed, my application-to-be will be loaded with Autocad entities. So, if the type library issue turns out to be the problem, I will have a lot of re-coding to do when converting the VBA macro into a VB executable.

In fact, I hope that the cause of my problem is less discouraging. As mentioned, I found out that the version specification in the CreateObject argument is ".16.2" for Autocad 2006. Could it be that this specification is the same for Autocad 2006 LT and Autocad 2006 full version, which might cause a conflict on my customers system? If so, a simple solution would be to use only the GetObject statement and if this causes an error, display a Messagebox urging the user to (exclusively) launch Autocad 2006 full version, and suspend further execution until he has done so. Maybe something like this:
Code: [Select]
Private Sub cmdLookForOpenAutocad2006FullVersion() 'commandbutton
Dim strMsg As String
strMsg = "Please launch Autocad 2006 full version" & vbCr
strMsg = strMsg & "(first close any other Autocad version)"
On Error Resume Next
Set AcadObj = GetObject(, "AutoCAD.Application.16.2")
If Err Then MsgBox (strMsg): Exit Sub 'Acad 2006 full version not open
'if not error, continue with the sub
« Last Edit: April 26, 2006, 04:28:13 AM by havano »

Bryco

  • Water Moccasin
  • Posts: 1864
Re: Lauching Autocad from a VB exe? No luck...
« Reply #3 on: April 26, 2006, 01:50:49 AM »
havano, I don't use vb (Only vba) so I don't have your problem with getting autocad but I do have the same type of problem getting  Excel. Once you
Dim Excel As Excel.Application
You are commited to setting the correct version of Excel on every machine that will run this code.
You do this by setting the correct reference in Tools-> References in the vbaide (where you code)
This is very tricky to do, but there is another way, late binding.
Late binding doesn't need any references and will look for the default version of excel on the computer.
But you now  must dim everything as object, see below.
    Dim Excel As Object         
    Dim ExcelSheet As Object
    Dim ExcelWorkbook As Object
    Dim strSaveName As String
    Dim i As Integer, j As Integer, k As Integer
   
    On Error Resume Next
    Set Excel = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Set Excel = CreateObject("Excel.Application")
    End If
    On Error GoTo 0
    Set ExcelWorkbook = Excel.Workbooks.Open(strXLpath)


Although  ExcelWorkbook  is dimmed as an object you still use it as a workbook and it has the properties of a workbook.

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #4 on: April 26, 2006, 02:13:26 AM »
Ah, now I understand the meaning of Late Binding much better. At least I think I do. Thanks Bryco!

Still, I think I will stick to early binding for this project: The customer insisted on Autocad 2006 (and 2006 alone) for compatibility, and who am I to argue?

One of the "competing" Autocad versions on my customer's systems is Autocad 2006 LT. Trying to access a Lite version from VB will result in an error anyway, no matter which type library.

So for now I'll concentrate on how to successfully launch or access Autocad 2006 Full Version from VB in a multi-Acad-version environment. Any suggestions on that are (also) highly appreciated.
« Last Edit: April 26, 2006, 05:18:49 AM by havano »

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #5 on: April 26, 2006, 05:39:14 AM »
OK. I am pretty confident that this code will work for my customers situation, but if anyone detects a snag please tell, I am reluctant to burden my customer (and our relationship) with yet another failing test. For example, will this code detect and trap errors due to Autocad LT interfering?

For convenience, I put the whole test program inside one form with three command buttons: Start Autocad, Draw Textstring and Exit. The code for keeping the form in the foreground is omitted in this snippet.

Option Explicit
Public AcadObj As AcadApplication
'----------
Private Sub StartAutocad_Click()
'look for Autocad 2006 (full version)
On Error Resume Next
Set AcadObj = GetObject(, "AutoCAD.Application.16.2")
If Err <> 0 Then
    Err.Clear
    Set AcadObj = CreateObject("AutoCAD.Application.16.2")
    If Err <> 0 Then ErrorMessage1: Exit Sub 'Get and Create failed
End If
'Get or Create Acad 2006 (full version?) was successful
Err.Clear: On Error GoTo 0
AcadObj.Visible = True
End Sub
'----------
Private Sub DrawTextstring_Click()
On Error Resume Next
Dim textObj As AcadText
Dim text As String
Dim insPt(0 To 2) As Double
Dim height As Double
' Define the text object
text = ". Test successful ."
insPt(0) = 2: insPt(1) = 2: insPt(2) = 0
height = 0.5
' Create the text object in model space
Set textObj = AcadObj.ActiveDocument.ModelSpace.AddText(text, insPt, height)
AcadObj.ZoomExtents
If Err <> 0 Then ErrorMessage2 'Autocad 2006 LT may have spoiled the fun...
End Sub
'----------
Private Sub Exit_Click()
On Error Resume Next 'just in case button was clicked without Acad loaded
AcadObj.Quit
Unload Me
End Sub
'----------
Private Sub ErrorMessage1()
Err.Clear: On Error GoTo 0
Dim strMsg As String
strMsg = "Can't find or start Autocad 2006 full version." & vbCr
strMsg = strMsg & "Please close all other versions and" & vbCr
strMsg = strMsg & "launch Autocad 2006 full version yourself."
MsgBox (strMsg)
End Sub
'----------
Private Sub ErrorMessage2()
Err.Clear: On Error GoTo 0
Dim strMsg As String
strMsg = "If Autocad 2006 full version has been opened" & vbCr
strMsg = strMsg & "but no text was drawn just now, then" & vbCr
strMsg = strMsg & "maybe Autocad 2006 LT is interfering."
MsgBox (strMsg)
End Sub
« Last Edit: April 26, 2006, 08:12:54 AM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #6 on: April 26, 2006, 07:54:48 AM »
Use Late Binding for these reasons... your client might upgrade to a newer version of acad within a few years.
this code will flunk before it is run because it uses a reference to an acad object and the interpreter will haltpre - scanning your code.

Option Explicit
Public AcadObj As Object
'----------
Private Sub StartAutocad_Click()
'look for Autocad 2006 (full version)
On Error Resume Next
Set AcadObj = GetObject(, "AutoCAD.Application.16.2")
If Err <> 0 Then
    Err.Clear
    Set AcadObj = CreateObject("AutoCAD.Application.16.2")
    If Err <> 0 Then ErrorMessage: Exit Sub 'Get and Create failed
End If
'Get or Create Acad 2006 (full version?) was successful
Err.Clear: On Error GoTo 0
AcadObj.Visible = True
End Sub
'----------
Private Sub DrawTextstring_Click()
On Error Resume Next
Dim textObj As Object  'this is a direct reference to the acad object as well
Dim text As String
Dim insPt(0 To 2) As Double
Dim height As Double
' Define the text object
text = ". Test successful ."
insPt(0) = 2: insPt(1) = 2: insPt(2) = 0
height = 0.5
' Create the text object in model space
Set textObj = AcadObj.ActiveDocument.ModelSpace.AddText(text, insPt, height)
AcadObj.ZoomExtents
If Err <> 0 Then ErrorMessage 'Autocad 2006 LT may have spoiled the fun...
End Sub
'----------
Private Sub Exit_Click()
On Error Resume Next 'just in case button was clicked without Acad loaded
AcadObj.Quit
Unload Me
End Sub
'----------
Private Sub ErrorMessage()
Err.Clear: On Error GoTo 0
Dim strMsg As String
strMsg = "Can't find or start Autocad 2006 full version." & vbCr
strMsg = strMsg & "Please close all other versions and" & vbCr
strMsg = strMsg & "launch Autocad 2006 full version yourself."
MsgBox (strMsg)
End Sub


The key to using late binding is earlly bind while developing being aware to change acad constants into their values and alter all assigning to acad objects into "as Object"
and removeing the reference. his will ensure future use at the cost of some speed loss

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #7 on: April 26, 2006, 08:24:57 AM »
Hi Berend, thanks for your comments and above all, your rewriting my code into a late-binding version.
I'll try it later, if all else fails. Btw you forgot to erase the Acadverson argument, which would frustrate the getobject and createobject part.

But please forgive me my slightly different view on the matter:  Being self-employed, my future income might largely or even solely consist of maintenance fees...
Catch my drift?  :kewl:

Groet!

Btw you forgot to erase the Acadverson property, which would frustrate GetObject and CreateObject because thereby the version-dependency would sneak back in.
« Last Edit: April 26, 2006, 08:54:58 AM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #8 on: April 26, 2006, 08:46:12 AM »
Yes I understand your way of doing business
but i do not think it will be the best way to continue screwing your customers.
(having a small business besides my daytime job)

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #9 on: April 26, 2006, 09:04:59 AM »
I had a hunch you would react like that. Sorry if I upset you.

I used to have your morals. That was about the time I had your monthly paycheck.

Would it help if I told you that I allowed the customer to "screw" me on this one, only hoping to get even some day? Believe me, I stil manage to keep close to the straight & narrow. The last thing I want or deserve is being looked down upon.

Enough about ethics, let's return to the subject.
« Last Edit: April 26, 2006, 09:20:40 AM by havano »

Mark

  • Custom Title
  • Seagull
  • Posts: 28725
Re: Lauching Autocad from a VB exe? No luck...
« Reply #10 on: April 26, 2006, 09:28:28 AM »
Enough about ethics, let's return to the subject.

Yes, please.  :-)
TheSwamp.org  (serving the CAD community since 2003)

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #11 on: April 26, 2006, 09:49:22 AM »
No apologies needed, i'm not easely upset, nor do i look down upon you.

apart from maintence stuff you still need to late bind. because the pre compiler or interpreter will flunk as soon as it detects the object reference is missing.
your code specifily wants to create an instance of version 16.2 so it wont work with 17.x nor 16.3
anyways. so you still can cash in on acad upgrades

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #12 on: April 26, 2006, 10:28:00 AM »
Not easily upset? I envy you, 'cause I am!

My code has an escape hatch. When coded with late binding, maybe the StartAutocad commandbutton will fail because of the version property, but once the user has launched Autocad manually, the DrawTextstring commandbutton (and other controls-in-the-making) should work fine.

My hesitation to indulge in late binding frenzies is not so much shrewdness as it is being just plain lazy.

Added later, to compensate for a post I deleted:
From what I read about late binding in the VB documentation, my program will become very slow, and I will have to do without the "cute little code completion helpers" while writing it. I think I will first develop the whole application on my machine using early binding, then demonstrate it to my client using my machine and then, as the last step, solve the problems I encounter while porting it to their environment. Maybe It would be a good idea to invoke the help of this community in that stage.
« Last Edit: April 27, 2006, 02:53:14 AM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #13 on: April 26, 2006, 11:20:40 AM »
this line will lock your macro.
Public AcadObj As AcadApplication
because it refers to the specific Acad object you are referencing now.
as it is public and in a vba module it wil be proccessed as soon as code in this module wil run.
only You can judge if thes could happen in your situation
I understand your lazyness, I have the same flaw.
But if you want a nice error advising to contact you with an adress and such. $$$$$ :wink:
it would help.

Have a nice day... (leaving the office)

off topic:
And don't envy my elephant skin I've got it due to many head bangings in the past.


Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16897
  • Superior Stupidity at its best
Re: Lauching Autocad from a VB exe? No luck...
« Reply #14 on: April 26, 2006, 02:16:03 PM »
Pretty close, except for the Poland France thingy ...

You can still have the cute little code helpers if you reference the library at design time, (early bind) then remove the binding (and all referenced bound objects) before building the executable. One thing to remember which we have not discussed is marshalling. Anytime you create an executable (something.exe) it will by necessity have to invoke marshalling to communicate with AutoCAD. In that instance, speed degradation will become a significant factor. You can prevent that by compiling to an ActiveX dll and calling your dll with VisualLisp or VBA. Then, late binding will be nearly negated as the dll will operate just as if it had been written right in the VBA IDE.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #15 on: April 26, 2006, 05:28:03 PM »
Havano,

You and I are on diffrent wave lengths on some things (I'm referring to what I wrote in my post and what you red in my post no more)
the $$$$ signs mend you could make a friendly way to persuade your customer to upgrade the software you are writing instead of locking or flunking. No more. I wasn't fishing for any deal.

perhaps the "it would help"should be: it would help to make that friendly error message and keeping control over what happens on your customers machine.... like a hyperlink to a mail to you so your customer could contact you easy and fast...etc etc.

I can however provide both exe's and the more efficient way... a dll's compiled in VB6.0 sp6

But I'm sure many members can. My suggestion to you is to really think through what you need, ask some questions on the difference between VB 6.0. and Acad vba because there are some. and carefully writ out the demands, needs options and so one you want... And post a assignment so everyone intrested can bid on it.




havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #16 on: April 27, 2006, 01:40:26 AM »
Thanks Keith and Dnereb for your reaction.
Sorry for removing my most recent posting, to which you reacted. When I woke op just now, I read it back and wasn't very proud of it. It was written in a "sinking state of mind". Please don't remove your reactions, they have been -and are- very helpful.

You are right Dnereb, I have had trouble understanding what you mean. It may have to do with me being a novice at VB(A) programming and with English not being my native language.

The bulk of the program I'm writing has little to do with Autocad anyway. The user must input some preferences and parameter values, VB(A) will do some sheet material cost-optimization and parametric drawing. It's hardly rocket science... There may be some other issues I would like to have your advice on. They will be posted as separate topics when they come up.

I wonder, has this binding issue already been discussed recently elsewhere on this forum? I did't find any, but maybe I wasn't looking in the right places. Or is the subject so trivial that no-one thinks it's worth mentioning?

Again Keith, Dnereb and Bryco, thanks for your highly appreciated help!
« Last Edit: April 27, 2006, 02:44:23 AM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #17 on: April 27, 2006, 02:46:54 AM »
Don't worry I'm no native American/English speaker as well. so you can put some of the misunderstandingd at my account as well.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16897
  • Superior Stupidity at its best
Re: Lauching Autocad from a VB exe? No luck...
« Reply #18 on: April 27, 2006, 08:21:17 AM »
To my knowledge, late binding has not been discussed at any length here.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

Draftek

  • Water Moccasin
  • Posts: 1501
Re: Lauching Autocad from a VB exe? No luck...
« Reply #19 on: April 27, 2006, 09:48:03 AM »
You will be better off forgetting the late binding and simply re-compiling your code every 3 years for a new compilation of the autocad type library.

In other words - an app that uses autocad.16 is good for 2004, 2005 and 2006.

By the time you need to recompile your probably not going to be using vb6 anyway.
Soli Deo Gloria

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #20 on: April 27, 2006, 10:23:04 AM »
Can you tell me why?
-you shouldn't use a dlll with late binding.
-why recompiling is better as writing code that wil run always no matter what version.
-You have to rewrite an app in VB 6.0 or in this case VBA into VB.net.

I will dig in .net this year but I can imagine myself maintaining apps written in VB6 in VB6 to avoid re writing for several weeks to add a little option button.

Draftek

  • Water Moccasin
  • Posts: 1501
Re: Lauching Autocad from a VB exe? No luck...
« Reply #21 on: April 27, 2006, 10:34:21 AM »
I'm a little confused over all your questions but to answer the main one:

Two words: Maintenance Nightmare.

Unless your project is tiny, the idea of replacing all autocad object references to object and then working on said project at a later date would be confusing or require having two projects synced. Either way I don't think it's a good idea.

Personally, I have built quite a large autocad dll utility app that I drop into my programs for use. I cannot imagine having to maintain all generic objects in it and totally wiping out my intellisense.

Not to mention there are features added in new compiles that will not work with older versions so knowing the version can be important.

I currently have two dll's one pre 2004 and one 2004 to 2006. I will drop the old one this year and add a new managed one for C#. I have about 1,000 apps deployed and have had no problems with having two versions of the programs provided on the cd's.
Soli Deo Gloria

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #22 on: April 27, 2006, 10:37:28 AM »
Hi Draftek,

If early binding is not the cause my VB test program returns errors when run by the customer, then wat is? Both he and I are using Autocad 2006, so the type libraries should be the same. The only problem I can see, is that his system also contains Autocad 2006 LT and Autocad R14.

And so we return to my original question!
« Last Edit: April 27, 2006, 04:43:25 PM by havano »

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16897
  • Superior Stupidity at its best
Re: Lauching Autocad from a VB exe? No luck...
« Reply #23 on: April 27, 2006, 10:55:19 AM »
Unless your project is tiny, the idea of replacing all autocad object references to object and then working on said project at a later date would be confusing or require having two projects synced. Either way I don't think it's a good idea.
I am working on a project that contains collectively 16000 lines of code and over 200 individual files. I always utilize late binding because it makes my program work on multiple versions ... This application is deployed over all versions from R2000 to R2007 without any issues ...

Personally, I have built quite a large autocad dll utility app that I drop into my programs for use. I cannot imagine having to maintain all generic objects in it and totally wiping out my intellisense.

IF you are familiar enough with the object model, you will find that you don't need the intellisense


Not to mention there are features added in new compiles that will not work with older versions so knowing the version can be important.

Indeed, which is why late binding is so great. If you cannot accurately predict what the client is going to do, then you MUST know your job and you MUST know the differences, otherwise you run the risk of appearing as a novice to your client.

I currently have two dll's one pre 2004 and one 2004 to 2006. I will drop the old one this year and add a new managed one for C#. I have about 1,000 apps deployed and have had no problems with having two versions of the programs provided on the cd's.
I currently have one single application that works on multiple versions and I only have a single version to maintain.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

Draftek

  • Water Moccasin
  • Posts: 1501
Re: Lauching Autocad from a VB exe? No luck...
« Reply #24 on: April 27, 2006, 11:12:00 AM »
havano: I'm not sure what your problem is because I'm not sure how your project is set up, but the 429 error can be deceiving the dll not loading may not be yours. Did you register your dll on the users's machine?

I have some startup code I have used for years without fail but I don't feel comfortable posting it because I did not write all of it.

You might try writing your app as a dll and passing the autocad application to it from a vba macro. That's the way I do 90% of my stuff.

Keith: I think it's better if I don't address your post...
Soli Deo Gloria

LE

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #25 on: April 27, 2006, 11:28:29 AM »
Here is what I neophyte in VB used some time ago...

Code: [Select]
Option Explicit
Option Compare Text
Declare Function RegQueryValueEx& Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey&, ByVal lpszValueName$, ByVal lpdwRes&, lpdwType&, ByVal lpDataBuff$, nSize&)
Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function ShellExecute Lib "shell32.dll" Alias _
      "ShellExecuteA" (ByVal hwnd As Long, ByVal lpszOp As _
      String, ByVal lpszFile As String, ByVal lpszParams As String, _
      ByVal lpszDir As String, ByVal FsShowCmd As Long) As Long
      Private Declare Function GetDesktopWindow Lib "user32" () As Long



Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_CLASSES_ROOT = &H80000000
Const KEY_QUERY_VALUE = &H1&
Const KEY_ENUMERATE_SUB_KEYS = &H8&
Const KEY_NOTIFY = &H10&
Const READ_CONTROL = &H20000
Const STANDARD_RIGHTS_READ = READ_CONTROL
Const KEY_READ = STANDARD_RIGHTS_READ Or KEY_QUERY_VALUE Or KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY
Const SW_SHOWNORMAL = 1
Const SE_ERR_FNF = 2&
Const SE_ERR_PNF = 3&
Const SE_ERR_ACCESSDENIED = 5&
Const SE_ERR_OOM = 8&
Const SE_ERR_DLLNOTFOUND = 32&
Const SE_ERR_SHARE = 26&
Const SE_ERR_ASSOCINCOMPLETE = 27&
Const SE_ERR_DDETIMEOUT = 28&
Const SE_ERR_DDEFAIL = 29&
Const SE_ERR_DDEBUSY = 30&
Const SE_ERR_NOASSOC = 31&
Const ERROR_BAD_FORMAT = 11&

Private Function GetAppPath(subkey As String, sAppEntry As String) As String
Dim s As String * 255, sAppPath As String
Dim lAppKey As Long, lType As Long, lLen As Long, lRC As Long
    lLen = Len(s)
    lRC = RegOpenKeyEx(HKEY_CLASSES_ROOT, sAppEntry, 0, KEY_READ, lAppKey)
    If lRC <> 0 Then Exit Function
    lRC = RegQueryValueEx( _
            lAppKey, _
            subkey, _
            0, _
            lType, _
            s, _
            lLen)
    's = Left$(s, lLen - 6)
    GetAppPath = Mid(s, 2, lLen - 8) 'Left$(s, lLen - 5)
End Function

 Function StartDoc(DocName As String, Param As String, Dir As String) As Long
          Dim Scr_hDC As Long
          Scr_hDC = GetDesktopWindow()
          StartDoc = ShellExecute(Scr_hDC, "Open", DocName, _
          Param, Dir, SW_SHOWNORMAL)
      End Function

Sub Main()
   
   Dim version As String
   Dim result As Boolean
   Dim sAcadEntry As String
   
   On Error Resume Next
   
   sAcadEntry = "AutoCAD.Drawing.16\shell\open\command"
   version = GetAppPath("", sAcadEntry)
   
   If StrConv(version, 1) Like "*ACAD.EXE" <> True Then
    MsgBox ("El programa AutoCAD Ver. 2004 no se encuentra instalado. \nPor favor refiérase al Manual del Usuario.")
    End
   End If
   
   'result = Shell(version & " /b draftteam.scr", 1)
   Dim r As Long, msg As String, Dir As String
          Dir = App.Path
          r = StartDoc(version, " /b draftteam.scr", Dir)
          If r <= 32 Then
              'There was an error
              Select Case r
                  Case SE_ERR_FNF
                      msg = "Archivo ejecutable de AutoCAD no encontrado."
                  Case SE_ERR_PNF
                      msg = "Ruta de AutoCADno encontrada"
                  Case SE_ERR_ACCESSDENIED
                      msg = "Acceso denegado de AutoCAD"
                  Case SE_ERR_OOM
                      msg = "Memoria insuficient"
                  Case SE_ERR_DLLNOTFOUND
                      msg = "DLL no encontrado"
                  Case SE_ERR_SHARE
                      msg = "Error de memoria"
                  Case SE_ERR_ASSOCINCOMPLETE
                      msg = "Incompleta o asociación de archivo inválida."
                  Case SE_ERR_DDETIMEOUT
                      msg = "DDE finalizó"
                  Case SE_ERR_DDEFAIL
                      msg = "Transacción DDE fallida."
                  Case SE_ERR_DDEBUSY
                      msg = "DDE ocupado"
                  Case SE_ERR_NOASSOC
                      msg = "No hay asociación para extensión de archivo."
                  Case ERROR_BAD_FORMAT
                      msg = "Ejecutable inválido."
                  Case Else
                      msg = "Error desconocido."
              End Select
              MsgBox msg
              End
          End If
   'wait 20 seconds to let AutoCAD open
   Dim TimeNow As Double
   Dim TimeEnd As Double
   TimeNow = Hour(Now()) + (Minute(Now()) / 60#) + (Second(Now()) / 3600#)
   TimeEnd = TimeNow + (20# / 3600#)
   
   
   Dim objAcad As Object
   Set objAcad = GetObject(, "AutoCAD.Application")
   
   While TimeNow < TimeEnd And (objAcad Is Nothing = True)
      Set objAcad = GetObject(, "AutoCAD.Application")
      TimeNow = Hour(Now()) + (Minute(Now()) / 60#) + (Second(Now()) / 3600#)
   Wend
 
   Dim preferences As Object
   Set preferences = objAcad.preferences
   Dim sPath As String
   sPath = preferences.Files.SupportPath
   If sPath <> "" Then
   Dim DttPath As String
   DttPath = objAcad.ActiveDocument.GetVariable("DWGPREFIX")
   Dim LDttPath As Integer
   LDttPath = Len(DttPath)
   If Right(DttPath, 1) = "\" Then
        DttPath = Left(DttPath, LDttPath - 1)
   End If
   'Add the path if does not exist
   If StrConv(sPath, 1) Like "*" & StrConv(DttPath, 1) & "*" <> True Then
        preferences.Files.SupportPath = sPath & ";" & DttPath
   End If
   End If
   Set objAcad = Nothing
   Set preferences = Nothing
   
End Sub

Then, having a filename.SCR to call a lisp file to be loaded....

HTH.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16897
  • Superior Stupidity at its best
Re: Lauching Autocad from a VB exe? No luck...
« Reply #26 on: April 27, 2006, 11:36:50 AM »
I just had a thought ... it may not be the AutoCAD object at all .. if you are referencing ANY files on your system, any type libraries that your client DOES NOT have, then it may throw the 429 error. The best way to identify if that is the problem, you should remove any unused references from your compiled executable, identify the referenced file names and versions, then request that your client identify that he has those files installed. The 13 error is a whole lot more incidious. It can be something as simple as an unexpected data type, a missing registry setting, or a missing file.

Draftek: I understand .. as is your perogative
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #27 on: April 27, 2006, 03:02:35 PM »
Thanks LE, I will try to decipher the code you posted, maybe a little higher up on my learning curve of VB and Spanish.

You may be right there, Keith. In the references list I checked a lot of libraries that I thought might have something to do with Autocad. If I didn't actually use a reference it wouldnt hurt either, I thought. Maybe I thought wrong.

On the other hand, I tried my test programs on a PC with nothing but Windows XP Home Edition and a typical install of Autocad 2006, and they al worked fine. Would it matter if my customer used XP Professional? I use a function that calls the user32.dll in order to keep my VB-form on top even after Autocad opens:
Code: [Select]
Declare Function SetWindowPos Lib "user32" _
  (ByVal hwnd As Long, _
  ByVal hWndInsertAfter As Long, _
  ByVal x As Long, ByVal y As Long, _
  ByVal cx As Long, ByVal cy As Long, _
  ByVal wFlags As Long) As Long
Public Const SWP_NOMOVE = &H2
Public Const SWP_NOSIZE = &H1
Public Const HWND_TOPMOST = -1
Public Const HWND_NOTOPMOST = -2
Could that cause the problem?

This answers your question as well Draftek, in my test programs (.EXE) I only call this user32.dll and the generic Autocad library/libraries. Shouldn't they all have been registered during the Windows and Autocad install?
« Last Edit: April 27, 2006, 03:10:05 PM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #28 on: April 27, 2006, 03:30:19 PM »
user32.dll is on my XP pro system and shouldn't be a problem. If you doubt avalibility you could check on www.allapi.net
they have good documentation on Api's download and install the .chm and you can use it as a documentation and library on API's. It also includes info on what api is availeble on which windows platform.
I still think your line:
Public AcadObj As AcadApplication
is the killer because it's a public and evaluated before you probably realize.
(read about the scope of variables to figer out why)



havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #29 on: April 27, 2006, 04:05:24 PM »
Hi again Dnereb,

My test program consists essentially of the code I posted earlier (3 commandbuttons in a single form) and hereabove (one function in a single module). So I could easily declare it as private. I just did, no problem here. Would that do the trick in my customer's environment? Having (re)read the scope tutorial I still don't see why.
« Last Edit: April 27, 2006, 04:11:52 PM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #30 on: April 27, 2006, 05:15:08 PM »
If it's just in one function couldn't you make it Local or Static?
If this fiunction only will be used when acad 61.2 is present you don't have to worrie, although i still think you should late bind. The way I do "it" this way:
I write the initial code early bound. (intellisense is a blessing) but on each line I early bind I make a remark 'As Object
So is I wan't to compile I save a copy first and sears for 'As Object and alter these lines to late bind.
and compile .

You seem to wonder why it make a diffrence...well how could a variable that's public not be proccessed if your code can adress it from everywhere...


havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #31 on: April 27, 2006, 05:31:10 PM »
I haven't got a clue...

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #32 on: April 27, 2006, 05:41:40 PM »
It is preproccessed to assign the propper object types to all Public type's amongst many other things....
This means
Public My_acad as AcadApplication
is assigned a V-table (a definition of how the object structure is) but the pre compiler will give an error because this object definition is not availeble on a machine without Acad 16.2 installed.... hence the error.

If a variable is local the v-table wil be assigned a the moment the code starts the function.
I know this is pretty technical but that's a coding hazzard you can not avoid   :roll:

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #33 on: April 27, 2006, 06:02:38 PM »
But that's exactly my point: Acad 16.2 IS installed.

Draftek

  • Water Moccasin
  • Posts: 1501
Re: Lauching Autocad from a VB exe? No luck...
« Reply #34 on: April 28, 2006, 08:14:22 AM »
You might try a 'repair registry' on the problem autocad installation.

Soli Deo Gloria

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #35 on: April 28, 2006, 08:21:08 AM »
But that's exactly my point: Acad 16.2 IS installed.

He has either an LT version installed or another version.

Hold on I'll make a .exe to read the acad registry...should have something similar hanging around somewhere.

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #36 on: April 28, 2006, 08:52:27 AM »
The customer has Acad 2006 full version AND Acad 2006 LT AND Acad R14 on his system...

Draftek

  • Water Moccasin
  • Posts: 1501
Re: Lauching Autocad from a VB exe? No luck...
« Reply #37 on: April 28, 2006, 08:56:12 AM »
First of all, you don't need the minor version .2 I don't believe.

Second, if they installed LT after the full version you could have a registry problem and the repair registry of autocad will clear that up.

I've had problems with autodesk software Inventor, Autocad, ADT, Mechanical, etc. Messing the registry up of earlier installs. Microsoft products may do the same thing.

Just a few years ago, If we had a tech support call, one of the first things asked was "Did you install MS Office after you installed autocad?"
Soli Deo Gloria

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #38 on: April 28, 2006, 09:32:12 AM »
just to be sure run this at your customer.
it will count and read all versions still having keys in his register.


havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #39 on: April 28, 2006, 09:34:27 AM »
Meantime, I mailed the customer a new version of the test executable, with private object declaration and late binding. Also I advised him -regardless of the test's outcome- to get rid of Acad LT and try the earlier test programs again, because even with this tiny test program I notice a drop in speed, probably because of the late binding.

Great little program, Dnereb! I'll wait for the test results (don't want to swamp the customer with e-mails, options and assignments) and then send him the version detector. Thanks!
« Last Edit: April 29, 2006, 06:47:12 PM by havano »

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #40 on: April 29, 2006, 12:42:48 PM »
reading up on com and marshalling...I found that your error also could be created if your customer moved or renamed
the autocad directory or a folder it's part of. this way the register is pointing at wrong place for the information to create the object.

havano

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #41 on: April 29, 2006, 06:46:19 PM »
Since the customer has 3 versions of Autocad on his system, chances are the Autocad 2006 full version is not in the default directory. However I don't think he has changed the directory name after the installation.

Yesterday I finally bought myself a notebook, so I will now be able to go to the customer and do some trial-and-error coding on the spot.

Dnereb

  • Guest
Re: Lauching Autocad from a VB exe? No luck...
« Reply #42 on: April 30, 2006, 04:45:42 AM »
Just be sure to ask if he did before you blow your brains. :-)