顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2011年5月23日 星期一

C#呼叫C++ dll (unmanaged)

這個方法不記下來,我怕我又會忘記。
在C++部份,先產生一個win32dll專案。接著把你想要的程式碼加入檔案中。
例如:
 #include<stdlib.h>
int string_length(char* str)
{
    int size = strlen(str);
    TCHAR unicode_string[50];
    mbstowcs(unicode_string, str, size+1);
    OutputDebugString(unicode_string);
    return strlen(str);
}
接下來在C#部份如下:
using System.Runtime.InteropServices;

namespace c_sharp_call_dll
{
    public partial class Form1 : Form
    {
        [DllImport("sample_cpp_dll.dll")]
        static extern int string_length(string str);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i = 15;
            MessageBox.Show(string_length(textBox1.Text).ToString());
        }
    }
}

C#控制滑鼠移動

在C++中,可以使用SetCursorPos以及mouse_event來操作滑鼠移動。
在C#中使用這兩個函式,需要一些小修改。

首先宣告:
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
使用的時候如下:
按一下左鍵(我不知道為什麼要呼叫四次mouse_event)
mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y , 0,0);
mouse_event(MOUSEEVENTF_LEFTUP, X, Y , 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y , 0,0);
mouse_event(MOUSEEVENTF_LEFTUP, X, Y , 0, 0);
將滑鼠移動到某個點:
SetCursorPos(X, Y);

C#呼叫外部程式

在C/C++中,我常用system()來呼叫外部程式。
 C#也有類似的作法,可以參考System.Diagnostics.Process類別說明。
 http://msdn2.microsoft.com/zh-tw/library/system.diagnostics.process(VS.80).aspx

網址上的範例已經寫得很清楚了,所以我不用再寫範例了。 
 
其實在C++中,還可以呼叫Win32 API
ShellExec 來啟動外部程式。
不過這個函數我沒有用過。
 

2011年5月21日 星期六

C#產生Word檔

先加入這幾行
using Microsoft.Office.Interop.Word;
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using System.Diagnostics;

然後先這樣:
           Word.ApplicationClass oWord = new Word.ApplicationClass();
            oWord.Visible = true;
            Word.Documents oDocs = oWord.Documents;
            object oFile = "c:\\doc1.doc";

            object oMissing = System.Reflection.Missing.Value;
            Word._Document oDoc = oDocs.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

 處理完之後再這樣:
             oDoc.SaveAs(ref oFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,ref oMissing,ref oMissing,
ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,
ref oMissing);
            // Quit Word and clean up.
            oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject (oDoc);
            oDoc = null;
            System.Runtime.InteropServices.Marshal.ReleaseComObject (oDocs);
            oDocs = null;
            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject (oWord);
            oWord = null;

C# 產生Excel檔

更多資訊可以參考:
http://www.codeproject.com/office/fasterexcelaccesstoc.asp
以及:
http://www.microsoft.com/downloads/details.aspx?familyid=3C9A983A-AC14-4125-8BA0-D36D67E0F4AD&displaylang=en

 這似乎是讀檔:
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
//using Excel;
namespace cs_using_excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
string Path = @"c:\test.xls";
// initialize the Excel Application class
Microsoft.Office.Interop.Excel.ApplicationClass app = new ApplicationClass();
// create the workbook object by opening the excel file.

Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(Path,
0,
true,
5,
"",
"",
true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
// get the active worksheet using sheet name or active sheet
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
object rowIndex = 2;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
rowIndex = 2 + index;
string firstName = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
index++;
}
}
catch (Exception ex)
{
app.Quit();
Console.WriteLine(ex.Message);
}
}
}
}
這似乎是寫檔:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace test_cs_console
{
    class Program
    {
        public static void Main(string[] args)
        {

            #region Uncomment the code in this region to run the TimedAccess class
            // TimedAccess timedAccess = new TimedAccess();
            // timedAccess.Read();
            // return;
            #endregion

            ApplicationClass app = new ApplicationClass();
            Workbook book = null;
            Worksheet sheet = null;
            Range range = null;

            try
            {
                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayAlerts = false;

                string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

                //book = app.Workbooks.Open(execPath + @"\..\..\Book1.xls", Missing.Value, Missing.Value, Missing.Value
                //                                  , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                //                                 , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                //                                , Missing.Value, Missing.Value, Missing.Value);
                book = app.Workbooks.Add(Missing.Value);
                sheet = (Worksheet)book.Worksheets[1];

                sheet.get_Range("A1", "A1").Value2="啦啦";

                book.SaveAs(execPath + @"\..\..\test.xls", Missing.Value, Missing.Value, Missing.Value
                                                  , Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value
                                                 , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                range = null;
                sheet = null;
                if (book != null)
                    book.Close(false, Missing.Value, Missing.Value);
                book = null;
                if (app != null)
                    app.Quit();
                app = null;
            }

        }
    }
}