Visual C kullanarak Microsoft Access'i otomatikleştirme #

Özet

Bu makalede, Microsoft Visual C# 2005 veya Microsoft Visual C# .NET kullanarak Microsoft Access'i otomatikleştirme işlemleri gösterilmektedir. Konular ve örnek kod, aşağıdakileri nasıl yapacağınızı gösterir:

  • Access'te bir veritabanı açın.
  • Access raporunu yazdırma veya önizleme.
  • Access formunu gösterme ve düzenleme.
  • Parola korumalı bir veritabanını açtığınızda veya kullanıcı düzeyi güvenlik açıkken iletişim kutularından kaçının.
  • Access Çalışma Zamanı'nı otomatikleştirme.

Otomasyon ile ADO.NET karşılaştırması

Geliştirici, Visual C# 2005 veya Visual C# .NET'ten bir Microsoft Access veritabanıyla çalışmak için iki ayrı teknoloji kullanabilir: Otomasyon ve Microsoft ADO.NET.

access veritabanındaki tablolar ve sorgular gibi veri nesneleriyle çalışmak istiyorsanız tercih edilen teknoloji ADO.NET. Otomasyon'u yalnızca Access raporunu yazdırma veya önizleme, Access formunu görüntüleme veya Access makrolarını çağırma gibi Microsoft Access uygulamasına özgü özelliklere ihtiyacınız varsa kullanın.

Bu makalede Access'in nasıl otomatikleştirılacağı açıklanır. Makalede ADO.NET tartışılmaz. ADO.NET hakkında bilgi için, Microsoft Bilgi Bankası'ndaki makaleleri görüntülemek üzere aşağıdaki makale numaralarına tıklayın:

  • 306636 ADO 2005 ve Visual C# 2005 kullanarak veya ADO.NET ve Visual C# .NET kullanarak veritabanına bağlanma ve komut çalıştırma

  • 314145 Visual C# .NET kullanarak veritabanından DataSet nesnesi doldurma

  • 307587 Visual C# 2005 veya Visual C# .NET kullanarak DataSet nesnesinden veritabanı güncelleştirme

Otomasyon bir Bileşen Nesne Modeli (COM) teknolojisidir. Otomasyon, Visual C# .NET gibi dillerde yazılmış uygulamaların diğer uygulamaları program aracılığıyla denetlemesine olanak tanır. Bir Microsoft Office uygulamasını otomatikleştirdiğinizde, bu uygulamanın bir örneğini bellekte çalıştırır ve ardından uygulamanın nesne modelini çağırarak bu uygulamada çeşitli görevleri gerçekleştirirsiniz. Access ve diğer Microsoft Office uygulamalarıyla, kullanıcı arabirimi aracılığıyla el ile gerçekleştirebileceğiniz eylemlerin neredeyse tümü Otomasyon kullanılarak program aracılığıyla da gerçekleştirilebilir.

Access bu programlı işlevselliği bir nesne modeli aracılığıyla kullanıma sunar. Nesne modeli, Access'in mantıksal bileşenlerine karşılık gelen sınıflar ve yöntemler koleksiyonudur. Visual C# .NET'ten nesne modeline erişmek için tür kitaplığına bir proje başvurusu ayarlayabilirsiniz.

Ortak Otomasyon Görevleri

Access'te Veritabanı Açma

Microsoft Access'i otomatikleştirdiğinizde, raporları yazdırma gibi yararlı görevleri gerçekleştirebilmeniz için önce veritabanını açmanız gerekir. Otomatikleştirdiğiniz Access örneğinde bir veritabanı açmak için, Uygulama nesnesinin OpenCurrentDatabase veya OpenAccessProject yöntemlerini kullanırsınız. Access'te aynı anda yalnızca bir veritabanı açabilirsiniz. Farklı bir veritabanıyla çalışmak için, başka bir veritabanı açmadan önce CloseCurrentDatabase yöntemini kullanabilirsiniz.

Access örneğindeki bir veritabanını açmak için System.Runtime.InteropServices.Marshal.BindToMoniker(<veritabanı> yolu) yöntemini de kullanabilirsiniz. Veritabanı Access örneğinde zaten açıksa, BindToMoniker söz konusu örneğin Application nesnesini döndürür. Aksi takdirde BindToMoniker yeni bir Access örneği başlatır ve belirtilen veritabanını açar.

Otomatikleştirdiğiniz Access örneğini belirttiğinizden, openCurrentDatabase veritabanını açmak için tercih edilen yöntemdir. Veritabanının nasıl açıldığını denetlemek için bağımsız değişkenler de sağlayabilirsiniz, örneğin:

Access.Application oAccess = null;

// Start a new instance of Access for Automation:
oAccess = new Access.ApplicationClass();

// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
   "c:\\mydb.mdb", //filepath
   true //Exclusive
   );

Access raporunu önizlemek veya yazdırmak için DoCmd nesnesinin OpenReport yöntemini çağırırsınız. OpenReport'u çağırdığınızda, geçirdiğiniz bağımsız değişkenlerden biri raporun ekranda önizlemesinin mi yoksa yazıcıya mı gönderileceğini belirler:

// Preview a report named Sales:
oAccess.DoCmd.OpenReport(
   "Sales", //ReportName
   Access.AcView.acViewPreview, //View
   System.Reflection.Missing.Value, //FilterName
   System.Reflection.Missing.Value //WhereCondition
   );

// Print a report named Sales:
oAccess.DoCmd.OpenReport(
   "Sales", //ReportName
   Access.AcView.acViewNormal, //View
   System.Reflection.Missing.Value, //FilterName
   System.Reflection.Missing.Value //WhereCondition
   );

Raporun Access'te görüntülenip görüntülenmeyeceğini veya yazıcıya gönderilip gönderilmediğini View bağımsız değişkeninin belirlediğine dikkat edin. Geçerli bir SQL WHERE yan tümcesi (WHERE sözcüğü olmadan) kullanıyorsanız WhereCondition bağımsız değişkeni raporun kayıt kümesini sınırlayabilir. İsteğe bağlı nesne parametrelerini atlamak için System.Reflection.Missing.Value'ı kullanabileceğinize dikkat edin.

Raporun önizlemesini görüntüleniyorsanız, Access'in ekranda görünür olması için Uygulama nesnesinin Visible özelliğini ayarladığınızdan emin olun. Bu şekilde, kullanıcı raporu Access penceresinde görüntüleyebilir.

Bir raporu veya veritabanındaki diğer nesneleri yazdırmanın başka bir yolu vardır. DoCmd nesnesinin PrintOut yöntemini kullanın. Bu örnekte, Veritabanı penceresinde Çalışanlar adlı bir rapor seçtikten sonra seçili nesneyi yazdırmak için PrintOut'a çağrıda bulunursunuz. PrintOut yöntemi, Access'teki Yazdır iletişim kutusuna karşılık gelen bağımsız değişkenler sağlamanıza olanak tanır:

// Select the Employees report in the database window:
oAccess.DoCmd.SelectObject(
   Access.AcObjectType.acReport, //ObjectType
   "Employees", //ObjectName
   true //InDatabaseWindow
   );

// Print 2 copies of the selected object:
oAccess.DoCmd.PrintOut(
   Access.AcPrintRange.acPrintAll, //PrintRange
   System.Reflection.Missing.Value, //PageFrom
   System.Reflection.Missing.Value, //PageTo
   Access.AcPrintQuality.acHigh, //PrintQuality
   2, //Copies
   false //CollateCopies
   );

Ya da bazı durumlarda, bir raporu yazdırmak için hem OpenReport hem de PrintOut yöntemlerini kullanmak isteyebilirsiniz. Çalışanlar raporunun yalnızca belirli bir çalışan için birden çok kopyasını yazdırmak istediğinizi varsayalım. Bu örnek ilk olarak OpenReport kullanarak Çalışanlar raporunu önizleme modunda açar ve kayıtları belirli bir çalışanla sınırlamak için WhereCondition bağımsız değişkenini kullanır. Ardından, Etkin nesnenin birden çok kopyasını yazdırmak için PrintOut kullanılır:

// Open the report in preview mode using a WhereCondition:
oAccess.DoCmd.OpenReport(
   "Employees", //ReportName
   Access.AcView.acViewPreview, //View
   System.Reflection.Missing.Value, //FilterName
   "[EmployeeID]=1" //WhereCondition
   );

// Print 2 copies of the active object: 
oAccess.DoCmd.PrintOut(
   Access.AcPrintRange.acPrintAll, //PrintRange
   System.Reflection.Missing.Value, //PageFrom
   System.Reflection.Missing.Value, //PageTo
   Access.AcPrintQuality.acHigh, //PrintQuality
   2, //Copies
   false //CollateCopies
   );

// Close the report preview window: 
oAccess.DoCmd.Close(
   Access.AcObjectType.acReport, //ObjectType
   "Employees", //ObjectName
   Access.AcCloseSave.acSaveNo //Save
   );

Access 2002, Printer nesnesini kullanıma sunar. Access yazıcı ayarlarını Access'in önceki sürümlerinden daha kolay özelleştirmek için bu nesneyi kullanabilirsiniz. Raporu yazdırmak için Access'teki Yazıcı nesnesini kullanma örneği için, Microsoft Bilgi Bankası'ndaki makaleyi görüntülemek üzere aşağıdaki makale numarasını tıklatın:

284286 Application.Printer nesnesinde değişiklikleri sıfırlama

Erişim Formunu Gösterme ve Düzenleme

Visual C# .NET'in çok güçlü form özellikleri vardır. Ancak, kullanıcının daha önce Access'te geliştirilmiş bir formu görüntülemesini istediğiniz zamanlar olabilir. Alternatif olarak, Access veritabanınızda bir sorgu veya rapor için ölçütler sağlayan bir formunuz olabilir ve raporu önizlemek veya yazdırmak için önce bu formu açmanız gerekir. Access formunu açmak ve göstermek için, DoCmd nesnesinin OpenForm yöntemini çağırırsınız:

// Show a form named Employees:
oAccess.DoCmd.OpenForm(
   "Employees", //FormName
   Access.AcFormView.acNormal, //View
   System.Reflection.Missing.Value, //FilterName
   System.Reflection.Missing.Value, //WhereCondition
   Access.AcFormOpenDataMode.acFormPropertySettings, //DataMode
   Access.AcWindowMode.acWindowNormal, //WindowMode
   System.Reflection.Missing.Value //OpenArgs
   );

Artık formdaki denetimleri düzenleyebilirsiniz.

Erişim Güvenliği İletişim Kutuları

Access'i otomatikleştirdiğinizde, veritabanını açmaya çalıştığınızda kullanıcı adı, parola veya her ikisini birden girmeniz istenebilir. Kullanıcı yanlış bilgi girerse, kodunuzda bir hata oluşur. Bazen bu iletişim kutularından kaçınmak ve bunun yerine Otomasyon kodunuzun kesintisiz çalışması için kullanıcı adını ve parolayı program aracılığıyla sağlamak isteyebilirsiniz.

Microsoft Access'te iki tür güvenlik vardır: parola korumalı veritabanları ve çalışma grubu dosyası (System.mdw) aracılığıyla kullanıcı düzeyinde güvenlik. Parola korumalı bir veritabanını açmaya çalışıyorsanız, veritabanı parolasını soran bir iletişim kutusu alırsınız. Kullanıcı düzeyinde güvenlik, parola korumalı veritabanından farklıdır. Kullanıcı düzeyinde güvenlik etkinleştirildiğinde Access, kullanıcının Access'te herhangi bir veritabanını açabilmesi için önce hem kullanıcı adı hem de parola isteyen bir oturum açma iletişim kutusu görüntüler.

Veritabanı Parolası İletişim Kutularını Önleme

Parolayla korunan bir veritabanını açıyorsanız, OpenCurrentDatabase yönteminin parolasını sağlayarak iletişim kutusundan kaçınabilirsiniz:

// Open a password-protected database in shared mode:
// Note: The bstrPassword argument is case-sensitive
oAccess.OpenCurrentDatabase(
   "c:\\mydb.mdb", //filepath
   false, //Exclusive
   "MyPassword" //bstrPassword
   );

Aşağıda, oAccess'in daha önce açık veritabanı olmayan bir Access örneğine ayarlandığı bir örnek verilmiştir. Bu kod, bir iletişim kutusunu önlemek için veritabanına parola sağlar:

string sDBPassword = "MyPassword"; //database password
DAO._DBEngine oDBEngine = oAccess.DBEngine;
DAO.Database oDB = oDBEngine.OpenDatabase("c:\\mydb.mdb",
   false, false, ";PWD=" + sDBPassword);
oAccess.OpenCurrentDatabase("c:\\mydb.mdb", false);
oDB.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDB);
oDB = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDBEngine);
oDBEngine = null;

oDB.Close, Access'teki veritabanını kapatmaz. Yalnızca DBEngine nesnesi aracılığıyla yapılan veritabanına yönelik DAO bağlantısını kapatır. OpenCurrentDatabase yöntemi kullanıldıktan sonra DAO bağlantısı artık gerekli değildir. oDB ve oDBEngine nesnelerini serbest bırakmak için koda dikkat edin. Kod tamamlandıktan sonra Access'in doğru şekilde çıkabilmesi için bu nesneleri kullanmanız gerekir.

Erişim Güvenliği Oturum Açma İletişim Kutularını Önleme

Access'te kullanıcı düzeyinde güvenlik açıksa, kullanıcıdan hem kullanıcı adı hem de parola isteyen bir oturum açma iletişim kutusu istenir. Access nesne modeli kullanılarak kullanıcı adı ve parola belirtilemez. Bu nedenle, Access'i otomatikleştirirken oturum açma iletişim kutusundan kaçınmak istiyorsanız, önce Msaccess.exe dosyasını başlatmanız ve kullanıcı adını ve parolasını belirtmek için /user ve /pwd komut satırı anahtarlarını sağlamanız gerekir. Daha sonra, Access'in çalışan örneğinin Uygulama nesnesini almak için GetActiveObject veya BindToMoniker kullanabilirsiniz, böylece Otomasyon ile devam edebilirsiniz.

Access Çalışma Zamanını Otomatikleştirme

Microsoft Office Developer Edition, Microsoft Office Geliştirici Araçları'nı (MOD) içerir. Access geliştiricileri MOD kullanarak Access uygulamaları oluşturabilir ve Access'in perakende sürümüne sahip olmayan kullanıcılara dağıtabilir. Kullanıcı Access uygulamasını Access'in perakende sürümüne sahip olmayan bir bilgisayara yüklediğinde, Access'in Çalışma Zamanı sürümü yüklenir. Access Çalışma Zamanı yüklenir ve perakende sürümü gibi kaydedilir. Yürütülebilir dosya Msaccess.exe olarak da adlandırılır. Access Çalışma Zamanı bir Access uygulamasının istemci bilgisayarda çalışmasına izin verir, ancak Access Çalışma Zamanı kullanıcının yeni uygulamalar geliştirmesine veya mevcut uygulamaların tasarımını değiştirmesine izin vermez.

Access Çalışma Zamanı bir veritabanıyla başlatılmalıdır. Bu gereksinim nedeniyle, Access Çalışma Zamanı'nı otomatikleştirmek istiyorsanız, Msaccess.exe başlatmanız ve açılacak bir veritabanı belirtmeniz gerekir. Uygulama nesnesini almak için GetActiveObject veya BindToMoniker kullandıktan sonra Access Çalışma Zamanı'nı otomatikleştirebilirsiniz. Access Çalışma Zamanı'nı otomatikleştirmeye çalışırken bu yaklaşımı kullanmıyorsanız örneği örneklemeye çalıştığınızda aşağıdaki gibi bir hata iletisi alırsınız:

System.Runtime.InteropServices.COMException (0x80080005) Sunucu yürütmesi başarısız oldu.

Eksiksiz Örnek Visual C# 2005 veya Visual C# .NET Projesi Oluşturma

Aşağıdaki adım adım örneği kullanmak için Northwind örnek veritabanının yüklü olduğundan emin olun. Varsayılan olarak, Microsoft Access 2000 örnek veritabanlarını aşağıdaki yola yükler:

C:\Program Files\Microsoft Office\Office\Samples

Microsoft Access 2002 aşağıdaki yolu kullanır:

C:\Program Files\Microsoft Office\Office10\Samples

Microsoft Office Access 2003 aşağıdaki yolu kullanır:

C:\Program Files\Microsoft\Office\Office11\Samples

Northwind örnek veritabanının Access 2002 veya Access 2003'te yüklü olduğundan emin olmak için Yardım menüsünde Örnek Veritabanları'na ve ardından Northwind Örnek Veritabanı'na tıklayın.

  1. Şu anda çalışmakta olan Access örneklerini kapatın.

  2. Microsoft Visual Studio .NET'i başlatın.

  3. Dosya menüsünde Yeni'ye ve ardından Proje'ye tıklayın. Visual C# Proje türlerinden Windows Uygulaması'nı seçin. Varsayılan olarak Form1 oluşturulur.

    Not Visual Studio 2005'te kodu değiştirmeniz gerekir. Varsayılan olarak, Windows Forms proje oluşturduğunuzda Visual C# projeye bir form ekler. Form, Form1 olarak adlandırılır. Formu temsil eden iki dosya Form1.cs ve Form1.designer.cs olarak adlandırılır. Kodu Form1.cs'de yazarsınız. Form1.designer.cs dosyası, Windows Forms Tasarımcısı'nın Denetimleri Araç Kutusu'ndan sürükleyip bırakarak gerçekleştirdiğiniz tüm eylemleri uygulayan kodu yazdığı yerdir.

    Visual C# 2005'teki Windows Forms Tasarımcısı hakkında daha fazla bilgi için aşağıdaki Microsoft Developer Network (MSDN) Web sitesini ziyaret edin:https://msdn.microsoft.com/en-us/library/ms173077.aspx

  4. Microsoft Access Nesne Kitaplığı'na başvuru ekleyin. Bunu yapmak için şu adımları uygulayın:

    1. Proje menüsünde Başvuru Ekle'ye tıklayın.
    2. COM sekmesinde Microsoft Access Nesne Kitaplığı'nı bulun ve Seç'e tıklayın.

    Not Visual Studio 2005'te. Seç'e tıklamanız gerekmez.

    Not Microsoft Office 2003, Birincil Birlikte Çalışma Derlemelerini (PIA) içerir. Microsoft Office XP PIA içermez, ancak indirilebilir.

  5. Başvuru Ekle iletişim kutusunda Tamam'a tıklayarak seçimlerinizi kabul edin.

    Not Access 10.0 nesne kitaplığına başvuruyorsanız ve başvuruyu eklemeyi denediğinizde hatalar alıyorsanız.

  6. Görünüm menüsünde Araç Kutusu'na tıklayarak araç kutusunu görüntüleyin.

  7. Form1'e beş radyo düğmesi denetimi ve bir düğme denetimi ekleyin.

  8. Tüm radyo düğmesi denetimlerini seçin ve ardından Boyut özelliğini 150.24 olarak ayarlayın.

  9. Form Yükleme olayı ve Düğme denetiminin Click olayı için olay işleyicileri ekleyin:

    1. Form1.cs'nin tasarım görünümünde Form1'e çift tıklayın.

      Formun Load olayının işleyicisi oluşturulur ve Form1.cs dosyasında görüntülenir.

    2. Görünüm menüsünde Tasarımcı'ya tıklayarak tasarım görünümüne geçin.

    3. Düğme1'e çift tıklayın.

      Düğmenin Click olayının işleyicisi oluşturulur ve Form1.cs'de görüntülenir.

  10. Form1.cs'de aşağıdaki kodu değiştirin

    private void Form1_Load(object sender, System.EventArgs e)
    {
    
    }
    
    private void button1_Click(object sender, System.EventArgs e)
    {
    
    } 
    

    Ile:

          private string msAction = null;
          // Commonly-used variable for optional arguments:
          private object moMissing = System.Reflection.Missing.Value;
    
    private void Form1_Load(object sender, System.EventArgs e)
          {
             radioButton1.Text = "Print report";
             radioButton2.Text = "Preview report";
             radioButton3.Text = "Show form";
             radioButton4.Text = "Print report (Security)";
             radioButton5.Text = "Preview report (Runtime)";
             button1.Text = "Go!";
             radioButton1.Click += new EventHandler(RadioButtons_Click);
             radioButton2.Click += new EventHandler(RadioButtons_Click);
             radioButton3.Click += new EventHandler(RadioButtons_Click);
             radioButton4.Click += new EventHandler(RadioButtons_Click);
             radioButton5.Click += new EventHandler(RadioButtons_Click);
          }
    
    private void RadioButtons_Click(object sender, System.EventArgs e)
          {
             RadioButton radioBtn = (RadioButton) sender;
             msAction = radioBtn.Text;
          }
    
    private void button1_Click(object sender, System.EventArgs e)
          {
             // Calls the associated procedure to automate Access, based
             // on the selected radio button on the form.
             switch(msAction)
             {
                case "Print report": Print_Report();
                   break;
                case "Preview report": Preview_Report();
                   break;
                case "Show form": Show_Form();
                   break;
                case "Print report (Security)": Print_Report_Security();
                   break;
                case "Preview report (Runtime)": Preview_Report_Runtime();
                   break;
             }
          }
    
    private void NAR(object o)
          {
             // Releases the Automation object.
             try // use try..catch in case o is not set
             {
                Marshal.ReleaseComObject(o);
             }
             catch{}
          }
    
    private Access.Application ShellGetDB(string sDBPath, string sCmdLine,
             ProcessWindowStyle enuWindowStyle, int iSleepTime)
          {
             //Launches a new instance of Access with a database (sDBPath)
             //using System.Diagnostics.Process.Start. Then, returns the
             //Application object via calling: BindToMoniker(sDBPath). Returns
             //the Application object of the new instance of Access, assuming that
             //sDBPath is not already opened in another instance of Access. To
             //ensure the Application object of the new instance is returned, make
             //sure sDBPath is not already opened in another instance of Access
             //before calling this function.
             // 
             //Example:
             //Access.Application oAccess = null;
             //oAccess = ShellGetDB("c:\\mydb.mdb", null,
             //  ProcessWindowStyle.Minimized, 1000);
    
    Access.Application oAccess = null;
             string sAccPath = null; //path to msaccess.exe
             Process p = null;
    
    // Enable exception handler:
             try
             {
                // Obtain the path to msaccess.exe:
                sAccPath = GetOfficeAppPath("Access.Application", "msaccess.exe");
                if (sAccPath == null)
    
    {
                   MessageBox.Show("Can't determine path to msaccess.exe");
                   return null;
                }
    
    // Make sure specified database (sDBPath) exists:
                if(!System.IO.File.Exists(sDBPath))
                {
                   MessageBox.Show("Can't find the file '" + sDBPath + "'");
                   return null;
                }
    
    // Start a new instance of Access passing sDBPath and sCmdLine:
                if(sCmdLine == null)
                   sCmdLine = @"""" + sDBPath + @"""";
                else
                   sCmdLine = @"""" + sDBPath + @"""" + " " + sCmdLine;
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = sAccPath;
                startInfo.Arguments = sCmdLine;
                startInfo.WindowStyle = enuWindowStyle;
                p = Process.Start(startInfo);
                p.WaitForInputIdle(60000); //max 1 minute wait for idle input state
    
    // Move focus back to this form. This ensures that Access
                // registers itself in the ROT:
                this.Activate();
    
    // Pause before trying to get Application object:
                System.Threading.Thread.Sleep(iSleepTime);
    
    // Obtain Application object of the instance of Access
                // that has the database open:
                oAccess = (Access.Application) Marshal.BindToMoniker(sDBPath);
                return oAccess;
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
                // Try to quit Access due to an unexpected error:
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
                return null;
             }
          }
    
    private Access.Application ShellGetApp(string sCmdLine,
             ProcessWindowStyle enuWindowStyle)
          {
             //Launches a new instance of Access using System.Diagnostics.
             //Process.Start then returns the Application object via calling:
             //GetActiveObject("Access.Application"). If an instance of
             //Access is already running before calling this function,
             //the function may return the Application object of a
             //previously running instance of Access. If this is not
             //desired, then make sure Access is not running before
             //calling this function, or use the ShellGetDB()
             //function instead. Approach based on Q316125.
             // 
             //Examples:
             //Access.Application oAccess = null;
             //oAccess = ShellGetApp("/nostartup",
             //  ProcessWindowStyle.Minimized);
             // 
             //-or-
             // 
             //Access.Application oAccess = null;
             //string sUser = "Admin";
             //string sPwd = "mypassword";
             //oAccess = ShellGetApp("/nostartup /user " + sUser + "/pwd " + sPwd,
             //  ProcessWindowStyle.Minimized);
    
    Access.Application oAccess = null;
             string sAccPath = null; //path to msaccess.exe
             Process p = null;
             int iMaxTries = 20; //max GetActiveObject attempts before failing
             int iTries = 0; //GetActiveObject attempts made
    
    // Enable exception handler:
             try
             {
                // Obtain the path to msaccess.exe:
                sAccPath = GetOfficeAppPath("Access.Application", "msaccess.exe");
                if(sAccPath == null)
                {
                   MessageBox.Show("Can't determine path to msaccess.exe");
                   return null;
                }
    
    // Start a new instance of Access passing sCmdLine:
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = sAccPath;
                startInfo.Arguments = sCmdLine;
                startInfo.WindowStyle = enuWindowStyle;
                p = Process.Start(startInfo);
                p.WaitForInputIdle(60000); //max 1 minute wait for idle input state
    
    // Move focus back to this form. This ensures that Access
                // registers itself in the ROT:
                this.Activate();
    
    tryGetActiveObject:
                // Enable exception handler:
                try
                {   
                   // Attempt to use GetActiveObject to reference a running
                   // instance of Access:
                   oAccess = (Access.Application)
                      Marshal.GetActiveObject("Access.Application");
                }
                catch
                {
                   //GetActiveObject may have failed because enough time has not
                   //elapsed to find the running Office application. Wait 1/2
                   //second and retry the GetActiveObject. If you try iMaxTries
                   //times and GetActiveObject still fails, assume some other
                   //reason for GetActiveObject failing and exit the procedure.
                   iTries++;
                   if(iTries < iMaxTries)
                   {
                      System.Threading.Thread.Sleep(500); //wait 1/2 second
                      this.Activate();
                      goto tryGetActiveObject;
                   }
                   MessageBox.Show("Unable to GetActiveObject after " +
                      iTries + " tries.");
                   return null;
                }
    
    // Return the Access Application object:
                return oAccess;
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
                // Try to quit Access due to an unexpected error:
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
                return null;
             }
          }
    
    private string GetOfficeAppPath(string sProgId, string sEXE)
          {
             //Returns path of the Office application. e.g.
             //GetOfficeAppPath("Access.Application", "msaccess.exe") returns
             //full path to Microsoft Access. Approach based on Q240794.
             //Returns null if path not found in registry.
    
    // Enable exception handler:
             try
             {
                Microsoft.Win32.RegistryKey oReg = 
                   Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey oKey = null;
                string sCLSID = null;
                string sPath = null;
                int iPos = 0;
    
    // First, get the clsid from the progid from the registry key
                // HKEY_LOCAL_MACHINE\Software\Classes\<PROGID>\CLSID:
                oKey = oReg.OpenSubKey(@"Software\Classes\" + sProgId + @"\CLSID");
                sCLSID = oKey.GetValue("").ToString();
                oKey.Close();
    
    // Now that we have the CLSID, locate the server path at
                // HKEY_LOCAL_MACHINE\Software\Classes\CLSID\ 
                // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx}\LocalServer32:
                oKey = oReg.OpenSubKey(@"Software\Classes\CLSID\" + sCLSID +
                   @"\LocalServer32");
                sPath = oKey.GetValue("").ToString();
                oKey.Close();
    
    // Remove any characters beyond the exe name:
                iPos = sPath.ToUpper().IndexOf(sEXE.ToUpper()); // 0-based position
                sPath = sPath.Substring(0, iPos + sEXE.Length);
                return sPath.Trim();
             }
             catch
             {
                return null;
             }
          }
    
    private void Print_Report()
          {
             // Prints the "Summary of Sales by Year" report in Northwind.mdb.
    
    Access.Application oAccess = null;
             string sDBPath = null; //path to Northwind.mdb
             string sReport = null; //name of report to print
    
    // Enable exception handler:
             try
             {
                sReport = "Summary of Sales by Year";
    
    // Start a new instance of Access for Automation:
                oAccess = new Access.ApplicationClass();
    
    // Determine the path to Northwind.mdb:
                sDBPath = oAccess.SysCmd(Access.AcSysCmdAction.acSysCmdAccessDir,
                   moMissing, moMissing).ToString();
                sDBPath = sDBPath + @"Samples\Northwind.mdb";
    
    // Open Northwind.mdb in shared mode:
                oAccess.OpenCurrentDatabase(sDBPath, false, "");
                // If using Access 10.0 object library, use this instead:
                //oAccess.OpenCurrentDatabase(sDBPath, false, null);
    
    // Select the report name in the database window and give focus
                // to the database window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport, true);
    
    // Print the report:
                oAccess.DoCmd.OpenReport(sReport,
                   Access.AcView.acViewNormal, moMissing, moMissing, 
                   Access.AcWindowMode.acWindowNormal, moMissing);
                // If using Access 10.0 object library, use this instead:
                //oAccess.DoCmd.OpenReport(sReport,
                //  Access.AcView.acViewNormal, moMissing, moMissing,
                //  Access.AcWindowMode.acWindowNormal, moMissing);
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
             }
             finally
             {
                // Release any Access objects and quit Access:
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
             }
          }
    
    private void Preview_Report()
          {
             // Previews the "Summary of Sales by Year" report in Northwind.mdb.
    
    Access.Application oAccess = null;
             Access.Form oForm = null;
             string sDBPath = null; //path to Northwind.mdb
             string sReport = null; //name of report to preview
    
    // Enable exception handler:
             try
             {
                sReport = "Summary of Sales by Year";
    
    // Start a new instance of Access for Automation:
                oAccess = new Access.ApplicationClass();
    
    // Make sure Access is visible:
                if(!oAccess.Visible) oAccess.Visible = true;
    
    // Determine the path to Northwind.mdb:
                sDBPath = oAccess.SysCmd(Access.AcSysCmdAction.acSysCmdAccessDir,
                   moMissing, moMissing).ToString();
                sDBPath = sDBPath + @"Samples\Northwind.mdb";
    
    // Open Northwind.mdb in shared mode:
                oAccess.OpenCurrentDatabase(sDBPath, false, "");
                // If using Access 10.0 object library, use this instead:
                //oAccess.OpenCurrentDatabase(sDBPath, false, null);
    
    // Close any forms that Northwind may have opened:
                while(oAccess.Forms.Count > 0)
                {   
                   oForm = oAccess.Forms[0];
                   oAccess.DoCmd.Close(Access.AcObjectType.acForm,
                      oForm.Name, Access.AcCloseSave.acSaveNo);
                   NAR(oForm);
                   oForm = null;
                }
    
    // Select the report name in the database window and give focus
                // to the database window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport, true);
    
    // Maximize the Access window:
                oAccess.RunCommand(Access.AcCommand.acCmdAppMaximize);
    
    // Preview the report:
                oAccess.DoCmd.OpenReport(sReport,
                   Access.AcView.acViewPreview, moMissing, moMissing, 
                   Access.AcWindowMode.acWindowNormal, moMissing);
                // If using Access 10.0 object library, use this instead:
                //oAccess.DoCmd.OpenReport(sReport,
                //  Access.AcView.acViewPreview, moMissing, moMissing,
                //  Access.AcWindowMode.acWindowNormal, moMissing);
    
    // Maximize the report window:
                oAccess.DoCmd.Maximize();
    
    // Hide Access menu bar:
                oAccess.CommandBars["Menu Bar"].Enabled = false;
                // Also hide NorthWindCustomMenuBar if it is available:
                try
                {
                   oAccess.CommandBars["NorthwindCustomMenuBar"].Enabled = false;
                }
                catch{}
    
    // Hide Report's Print Preview menu bar:
                oAccess.CommandBars["Print Preview"].Enabled = false;
    
    // Hide Report's right-click popup menu:
                oAccess.CommandBars["Print Preview Popup"].Enabled = false;
    
    // Release Application object and allow Access to be closed by user:
                if(!oAccess.UserControl) oAccess.UserControl = true;
                NAR(oAccess);
                oAccess = null;
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
                // Release any Access objects and quit Access due to error:
                NAR(oForm);
                oForm = null;
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
             }
          }
    
    private void Show_Form()
          {
             // Shows the "Customer Labels Dialog" form in Northwind.mdb
             // and manipulates controls on the form.
    
    Access.Application oAccess = null;
             Access.Form oForm = null;
             Access.Controls oCtls = null;
             Access.Control oCtl = null;
             string sDBPath = null; //path to Northwind.mdb
             string sForm = null; //name of form to show
    
    // Enable exception handler:
             try
             {
                sForm = "Customer Labels Dialog";
    
    // Start a new instance of Access for Automation:
                oAccess = new Access.ApplicationClass();
    
    // Make sure Access is visible:
                if(!oAccess.Visible) oAccess.Visible = true;
    
    // Determine the path to Northwind.mdb:
                sDBPath = oAccess.SysCmd(Access.AcSysCmdAction.acSysCmdAccessDir,
                   moMissing, moMissing).ToString();
                sDBPath = sDBPath + @"Samples\Northwind.mdb";
    
    // Open Northwind.mdb in shared mode:
                oAccess.OpenCurrentDatabase(sDBPath, false, "");
                // If using Access 10.0 object library, use this instead:
                //oAccess.OpenCurrentDatabase(sDBPath, false, null);
    
    // Close any forms that Northwind may have opened:
                while(oAccess.Forms.Count > 0)
                {   
                   oForm = oAccess.Forms[0];
                   oAccess.DoCmd.Close(Access.AcObjectType.acForm,
                      oForm.Name, Access.AcCloseSave.acSaveNo);
                   NAR(oForm);
                   oForm = null;
                }
    
    // Select the form name in the database window and give focus
                // to the database window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acForm, sForm, true);
    
    // Show the form:
                oAccess.DoCmd.OpenForm(sForm, Access.AcFormView.acNormal, moMissing,
                   moMissing, Access.AcFormOpenDataMode.acFormPropertySettings,
                   Access.AcWindowMode.acWindowNormal, moMissing);
    
    // Use Controls collection to edit the form:
    
    oForm = oAccess.Forms[sForm];
                oCtls = oForm.Controls;
    
    // Set PrintLabelsFor option group to Specific Country:
    
    oCtl = (Access.Control)oCtls["PrintLabelsFor"];
                object[] Parameters = new Object[1];
                Parameters[0] = 2; //second option in option group
                oCtl.GetType().InvokeMember("Value", BindingFlags.SetProperty,
                   null, oCtl, Parameters);
                NAR(oCtl);
                oCtl = null;
    
    // Put USA in the SelectCountry combo box:
                oCtl = (Access.Control)oCtls["SelectCountry"];
                Parameters[0] = true;
                oCtl.GetType().InvokeMember("Enabled", BindingFlags.SetProperty,
                   null, oCtl, Parameters);
                oCtl.GetType().InvokeMember("SetFocus", BindingFlags.InvokeMethod,
                   null, oCtl, null);
                Parameters[0] = "USA";
                oCtl.GetType().InvokeMember("Value", BindingFlags.SetProperty,
                   null, oCtl, Parameters);
                NAR(oCtl);
                oCtl = null;
    
    // Hide the Database Window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acForm, sForm, true);
                oAccess.RunCommand(Access.AcCommand.acCmdWindowHide);
    
    // Set focus back to the form:
                oForm.SetFocus();
    
    // Release Controls and Form objects:       
                NAR(oCtls);
                oCtls = null;
                NAR(oForm);
                oForm = null;
    
    // Release Application object and allow Access to be closed by user:
                if(!oAccess.UserControl) oAccess.UserControl = true;
                NAR(oAccess);
                oAccess = null;
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
                // Release any Access objects and quit Access due to error:
                NAR(oCtl);
                oCtl = null;
                NAR(oCtls);
                oCtls = null;
                NAR(oForm);
                oForm = null;
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
             }
          }
    
    private void Print_Report_Security()
          {
             //Shows how to automate Access when user-level
             //security is enabled and you wish to avoid the logon
             //dialog asking for user name and password. In this
             //example we're assuming default security so we simply
             //pass the Admin user with a blank password to print the
             //"Summary of Sales by Year" report in Northwind.mdb.
    
    Access.Application oAccess = null;
             string sDBPath = null; //path to Northwind.mdb
             string sUser = null; //user name for Access security
             string sPwd = null; //user password for Access security
             string sReport = null; //name of report to print
    
    // Enable exception handler:
             try
             {
                sReport = "Summary of Sales by Year";
    
    // Determine the path to Northwind.mdb:
                sDBPath = GetOfficeAppPath("Access.Application", "msaccess.exe");
                if(sDBPath == null)
                {
                   MessageBox.Show("Can't determine path to msaccess.exe");
                   return;
                }
                sDBPath = sDBPath.Substring(0, sDBPath.Length - "msaccess.exe".Length)
                   + @"Samples\Northwind.mdb";
                if(!System.IO.File.Exists(sDBPath))
                {
                   MessageBox.Show("Can't find the file '" + sDBPath + "'");
                   return;
                }
    
    // Specify the user name and password for the Access workgroup
                // information file, which is used to implement Access security.
                // Note: If you are not using the system.mdw in the default
                // location, you may include the /wrkgrp command-line switch to
                // point to a different workgroup information file.
                sUser = "Admin";
                sPwd = "";
    
    // Start a new instance of Access with user name and password:
                oAccess = ShellGetDB(sDBPath, "/user " + sUser + " /pwd " + sPwd,
                   ProcessWindowStyle.Minimized, 1000);
                //or
                //oAccess = ShellGetApp(@"""" + sDBPath + @"""" + 
                //  " /user " + sUser + " /pwd " + sPwd,
                //  ProcessWindowStyle.Minimized);
    
    // Select the report name in the database window and give focus
                // to the database window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport, true);
    
    // Print the report:
                oAccess.DoCmd.OpenReport(sReport,
                   Access.AcView.acViewNormal, moMissing, moMissing,
                   Access.AcWindowMode.acWindowNormal, moMissing );
                // If using Access 10.0 object library, use this instead:                       
                //oAccess.DoCmd.OpenReport(sReport,
                //  Access.AcView.acViewNormal, moMissing, moMissing,
                //  Access.AcWindowMode.acWindowNormal, moMissing);
             }
             catch(Exception e)
             {   
                MessageBox.Show(e.Message);
             }
             finally
             {
                // Release any Access objects and quit Access:
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
             }
          }
    
    private void Preview_Report_Runtime()
          {
             //Shows how to automate the Access Runtime to preview
             //the "Summary of Sales by Year" report in Northwind.mdb.
    
    Access.Application oAccess = null;
             Access.Form oForm = null;
             string sDBPath = null; //path to Northwind.mdb
             string sReport = null; //name of report to preview
    
    // Enable exception handler:
             try
             {
                sReport = "Summary of Sales by Year";
    
    // Determine the path to Northwind.mdb:
                sDBPath = GetOfficeAppPath("Access.Application", "msaccess.exe");
                if(sDBPath == null)
                {
                   MessageBox.Show("Can't determine path to msaccess.exe");
                   return;
                }
    
    sDBPath = sDBPath.Substring(0, sDBPath.Length - "msaccess.exe".Length)
                   + @"Samples\Northwind.mdb";
                if(!System.IO.File.Exists(sDBPath))
                {
                   MessageBox.Show("Can't find the file '" + sDBPath + "'");
                   return;
                }
    
    // Start a new instance of Access with a database. If the
                // retail version of Access is not installed, and only the
                // Access Runtime is installed, launches a new instance
                // of the Access Runtime (/runtime switch is optional):
                oAccess = ShellGetDB(sDBPath, "/runtime",
                   ProcessWindowStyle.Minimized, 1000);
                //or
                //oAccess = ShellGetApp(@"""" + sDBPath + @"""" + " /runtime",
                //  ProcessWindowStyle.Minimized);
    
    // Make sure Access is visible:
                if(!oAccess.Visible) oAccess.Visible = true;
    
    // Close any forms that Northwind may have opened:
                while(oAccess.Forms.Count > 0)
                {   
                   oForm = oAccess.Forms[0];
                   oAccess.DoCmd.Close(Access.AcObjectType.acForm,
                      oForm.Name, Access.AcCloseSave.acSaveNo);
                   NAR(oForm);
                   oForm = null;
                }
    
    // Select the report name in the database window and give focus
                // to the database window:
                oAccess.DoCmd.SelectObject(Access.AcObjectType.acReport, sReport, true);
    
    // Maximize the Access window:
                oAccess.RunCommand(Access.AcCommand.acCmdAppMaximize);
    
    // Preview the report:
                oAccess.DoCmd.OpenReport(sReport,
                   Access.AcView.acViewPreview, moMissing, moMissing,
                   Access.AcWindowMode.acWindowNormal, moMissing );
                // If using Access 10.0 object library, use this instead:
                //oAccess.DoCmd.OpenReport(sReport,
                //  Access.AcView.acViewPreview, moMissing, moMissing,
                //  Access.AcWindowMode.acWindowNormal, moMissing);
    
    // Maximize the report window:
                oAccess.DoCmd.Maximize();
    
    // Hide Access menu bar:
                oAccess.CommandBars["Menu Bar"].Enabled = false;
                // Also hide NorthWindCustomMenuBar if it is available:
                try
                {
                   oAccess.CommandBars["NorthwindCustomMenuBar"].Enabled = false;
                }
                catch{}
    
    // Release Application object and allow Access to be closed by user:
                if(!oAccess.UserControl) oAccess.UserControl = true;
                NAR(oAccess);
                oAccess =  null;
             }
             catch(Exception e)
             {
                MessageBox.Show(e.Message);
                // Release any Access objects and quit Access due to error:
                NAR(oForm);
                oForm = null;
                try // use try..catch in case oAccess is not set
                {
                   oAccess.Quit(Access.AcQuitOption.acQuitSaveNone);
                }
                catch{}
                NAR(oAccess);
                oAccess = null;
             }
          }
    
    
  11. Form1.cs'deki Using yönergelerine aşağıdaki kodu ekleyin:

    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Reflection; 
    
  12. Programı derlemek ve çalıştırmak için F5 tuşuna basın. Form1 görüntülenir.

  13. Raporu yazdır'a ve ardından Git!'e tıklayın. Print_Report yordamı Northwind veritabanından bir rapor yazdırır.

  14. Raporu önizle'ye ve ardından Git!'e tıklayın. Preview_Report yordamı, Northwind veritabanından bir raporun önizlemesini gösterir. Devam etmeye hazır olduğunuzda Access örneğini kapatın.

  15. Formu göster'e ve ardından Git!'e tıklayın. Show_Form yordamı, Northwind veritabanındaki Müşteri Etiketleri iletişim kutusu formunu görüntüler. Ayrıca formdaki seçenek grubunu "Belirli Ülke" olarak ayarlar ve listeden "ABD" öğesini seçer. Devam etmeye hazır olduğunuzda Access örneğini kapatın.

  16. Raporu yazdır (Güvenlik) seçeneğine ve ardından Git!'e tıklayın. Print_Report_Security yordamı, Access'i otomatikleştirmeyi ve kullanıcı düzeyi güvenlik açıksa oturum açma iletişim kutusunu önlemeyi gösterir. Bu örnekte, kullanıcı Yönetici boş bir parolayla geçirerek varsayılan oturum açmayı varsayın. Kod daha sonra Northwind veritabanında bir rapor yazdırır.

  17. Raporu önizleme (Çalışma zamanı) seçeneğine ve ardından Git!'e tıklayın. Preview_Report_Runtime yordamı, Access Çalışma Zamanı'nı otomatikleştirerek Northwind veritabanındaki bir raporun önizlemesini görüntülemeyi gösterir. Access'in perakende sürümü yüklüyse yordam düzgün çalışmaya devam eder. Devam etmeye hazır olduğunuzda Access örneğini kapatın.

Başvurular

Daha fazla bilgi için şu MSDN Web sitesini ziyaret edin: Visual Studio https://msdn.microsoft.com/en-us/library/aa188489(office.10).aspxile Microsoft Office Geliştirme Daha fazla bilgi için, Microsoft Bilgi Bankası'ndaki makaleleri görüntülemek üzere aşağıdaki makale numaralarına tıklayın:

317109 Office uygulaması Visual Studio .NET istemcisinden otomasyondan sonra kapatılmıyor

316126 Bir Office programının çalışan örneğini otomatikleştirmek için Visual C# kullanma