By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,825 Members | 1,254 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,825 IT Pros & Developers. It's quick & easy.

Opening Mdb bypassing AutoExec with C# Solved, but curious about why solution works

Expert 100+
P: 112
Hi,

I have been messing around with automating Access (I am attempting to actually manipulate the Access objects themselves so it requires going beyond data access) from a c# program (long story as to why, but any how...). I am dealing with databases that all have AutoExec macros within them which automatically run when the database opens, which I don't want the database to do. In Access this is bypassed by holding down the shift key. I have attempted to replicate doing this when opening from the C# program, in so doing I ported a piece of code over from VBA which did this very thing, using the SetKeyboardState API call. After monkeying around with the code a lot I finally arrived at this solution which does what I want, but I am not sure why:
Expand|Select|Wrap|Line Numbers
  1.    class OpenMdb
  2.     {
  3.        private const int VK_SHIFT = 0x10;
  4.         [DllImport("user32")]
  5.             public static extern long SetKeyboardState(ref byte lppbKeyStat);
  6.         [DllImport("user32")]
  7.              public static extern long SetFocus(long hwnd);
  8.         public static Access.Application NoAutoexec (int hWnd, string path, bool visible)
  9.         {
  10.             Access.Application app;
  11.             byte[] abytCodesSrc = new byte[256];
  12.             byte[] abytCodesDest = new byte[256];
  13.             app = new Access.Application();
  14.             app.Visible = visible;
  15.             abytCodesDest[VK_SHIFT] = 128;
  16.             SetKeyboardState(ref abytCodesDest[0]);
  17.             System.Windows.Forms.SendKeys.Send("+");
  18.             app.OpenCurrentDatabase(path, true, "");
  19.             SetFocus(hWnd);
  20.             return app;
  21.         } 
  22.     }
  23.  
The thing that has me puzzled is that the key to making this work was inserting the SendKeys statement. Sendkeys alone won't make this happen. The SetKeyboardState alone won't do what I am asking, but this seems to work. I think that I probably have a fundamental misunderstanding of what the SetKeyboardState API is doing. I'd like to figure out why the conjunction of the API and Sendkeys is behaving this way. Any ideas?
Aug 19 '08 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.