.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

I need do some action just before opening file.

7 REPLIES 7
Reply
Message 1 of 8
RamanSBV
605 Views, 7 Replies

I need do some action just before opening file.

Hi,

 

I need to do some action just before drawing file.

 

Please guide me how i can do it.

 


Regards,

Raman

7 REPLIES 7
Message 2 of 8


@RamanSBV wrote:
... I need to do some action just before drawing file...

These actions are secret? Can you explain exactly what to do? Which way the file is opened? Maybe you need to replace the command OPEN with own command?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 3 of 8

Not secrets Smiley Happy

 

I have to check either this file is valued file (means opening from some particular folder)

if file is opening from somewhere else  other than particular folder then I should not allow user to open the file and show some message.

 

 

 

Regards,

Raman

 

Message 4 of 8

Veto a particular command in AutoCAD

You can veto command OPEN do some action and open (or not open) file.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 5 of 8
Andrey_Bushman
in reply to: RamanSBV

...
App.DocumentCollection docMng = cad.DocumentManager;
docMng.DocumentLockModeChanged += new App.DocumentLockModeChangedEventHandler(docMng_DocumentLockModeChanged);
...


        static void docMng_DocumentLockModeChanged(object sender, App.DocumentLockModeChangedEventArgs e) {

            // Можно переопределить команду OPEN, подсовывая вместо "родного" диалогового окна открытия
            // файлов своё. Такой подход предоставит возможность выполнять предварительную проверку содержимого 
            // каталога открываемого файла и, в случае необходимости, блокировать открытие чертежа: например, если в каталоге 
            // находится доступный только для чтения файл acad*.lsp, или acad*.fas:

            if (settings.DisableDrawingOpeningFromDangerDir && string.Compare(e.GlobalCommandName, "OPEN", true) == 0) {
                e.Veto();
                //ShowOpenFileDialog(); // Так нельзя, иначе после моего диалогового окна почему-то
                // будет открываться "родное" окно выбора файлов AutoCAD.
                // Поэтому делаю так:
                cad.DocumentManager.MdiActiveDocument.SendStringToExecute("bush-open ", true, false, false);
            }

            // В случае необходимости, можно отключить автоматическую загрузку файлов acad*.lsp, или acad*.fas:
            if (settings.DisableAcadLispAutoloading && e.GlobalCommandName.Contains("s::startup"))
                e.Veto();
        }

        [Rtm.CommandMethod("bush-open", Rtm.CommandFlags.Modal)]
        public static void ShowOpenFileDialog() {
            CadWin.OpenFileDialog dialog = new CadWin.OpenFileDialog(
                String.Format("[{0}] {1}", Resource.startTitle, Resource.docOpenTitle),
                "", "dwg;dwt;dws;dxf", "", CadWin.OpenFileDialog.OpenFileDialogFlags.SearchPath);

            WinForms.DialogResult result = dialog.ShowDialog();

            if (result != Win.Forms.DialogResult.OK)
                return;

            if (!dialog.Filename.ToLower().StartsWith(CadSettings.Variables["ac-app"].Value)) {
                DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(dialog.Filename));

                if (!dir.Exists)
                    return;

                FileInfo[] files = dir.GetFiles("acad*.lsp", SearchOption.TopDirectoryOnly);
                FileInfo[] files2 = dir.GetFiles("acad*.fas", SearchOption.TopDirectoryOnly);
                FileInfo[] files3 = dir.GetFiles("acad*.mnl", SearchOption.TopDirectoryOnly);

                String fileName = String.Empty;
                try {
                    foreach (FileInfo[] collection in new FileInfo[][] { files, files2, files3 }) {
                        foreach (FileInfo item in collection) {
                            fileName = item.FullName;
                            item.Delete();
                            cad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(Resource.fileDeleted, fileName);
                        }
                    }
                }
                catch (Exception ex) {
                    Win.MessageBox.Show(String.Format(Resource.disableFileOpen, fileName, ex.Message),
                        Resource.warning, Win.MessageBoxButton.OK, Win.MessageBoxImage.Stop);
                    return;
                }
            }
            App.Document doc = cad.DocumentManager.Open(dialog.Filename);
            if (doc != null)
                cad.DocumentManager.MdiActiveDocument = doc;
        }

 

Message 6 of 8
norman.yuan
in reply to: RamanSBV

Well, handling DocumentLockModeChanged event and veto the change if the command is "OPEN" only works if the drawing is to be opened with command "OPEN". That is in the code you need to make decisioon by examine the DocumentLockModeChangedEventArgs.GlobalCommandName (say, if the name string contains upcase "OPEN"). However, sometime a drawing can be open without using command OPEN. For example, double-clicking a drawing in Windows Explorer, or click drawing "recent drawing list".

 

You may think hard: if you do not want user to open some drawing why can't you place these drawing file in a folder where the your is not allowed to access? Or maybe give them read-only access is sufficient (so they can still open but cannot save change back)?

 

I'd only consider vetoing open command as last option.

Message 7 of 8

@norman.yuan

 

Yes, you are right. Now I don't know how to disable drawings opening through an Explorer, or through an "Recent Drawing List". I remember, I have tried at past to close drawings after it was opened (via event's registration), but I couldn't did it (I've got Fatal Error).

 

Regards, Andrey.

 

Message 8 of 8
arcticad
in reply to: Andrey_Bushman

My Workaround for a smiliar issue was to make a stand alone program that didn't show up in the taskbar. Associate the file format with that new program. It would then open the drawings using COM and make the changes I wanted to the file, then pass the file off to Autocad.

This was all transparent to the user.

User would double click on a file -> File gets checked with COM, AutoCAD is run if needed -> If file passes, it is sent onto AutoCAD.

Just note if you are using COM, I found that the file would be in use by the external program and then it would open read only in AutoCAD, The solution was to copy the file into the users temp folder, with a unique name and then the modifications were done on that file then copied to overright the original. Then the copy is opened in AutoCAD.

This may have changed in 2013, as I have not tried it.

Then the external program waits untill AutoCAD closes and deletes the files in the temp folder, as they are still "in use" from COM.

If there is an easier way I would like to know.

---------------------------



(defun botsbuildbots() (botsbuildbots))

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost