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
- class OpenMdb
- {
- private const int VK_SHIFT = 0x10;
- [DllImport("user32")]
- public static extern long SetKeyboardState(ref byte lppbKeyStat);
- [DllImport("user32")]
- public static extern long SetFocus(long hwnd);
- public static Access.Application NoAutoexec (int hWnd, string path, bool visible)
- {
- Access.Application app;
- byte[] abytCodesSrc = new byte[256];
- byte[] abytCodesDest = new byte[256];
- app = new Access.Application();
- app.Visible = visible;
- abytCodesDest[VK_SHIFT] = 128;
- SetKeyboardState(ref abytCodesDest[0]);
- System.Windows.Forms.SendKeys.Send("+");
- app.OpenCurrentDatabase(path, true, "");
- SetFocus(hWnd);
- return app;
- }
- }