2010-09-03

C# firestream 讀檔、struct 和 byte 之間的轉換

using System.IO;
using System.Runtime.InteropServices;
using System;
 
//1. 把檔案讀成 Byte 形式
private byte[] readFile(string strFileName)
{
 
    byte[] buffer = null;
    FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
    try
    {
        BinaryReader br = new BinaryReader(fs);
        int len = System.Convert.ToInt32(fs.Length);
 
        buffer = br.ReadBytes(len);
 
    }
    finally
    {
        fs.Close();
    }
    return buffer;
}
 
//2. struct 轉成 byte
static byte[] StructToBytes(object structObj)
{
    int size = Marshal.SizeOf(structObj);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.StructureToPtr(structObj, buffer, false);
        byte[] bytes = new byte[size];
        Marshal.Copy(buffer, bytes, 0, size);
        return bytes;
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}
 
//3. byte 轉成 struct
static object BytesToStruct(byte[] bytes, Type strcutType)
{
    int size = Marshal.SizeOf(strcutType);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.Copy(bytes, 0, buffer, size);
        return Marshal.PtrToStructure(buffer, strcutType);
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}

2010-09-02

Unity 3D 隱藏視窗外框

Unity3D 若要客製化視窗的外框,就本人所知的方法為:

1. 隱藏原本的視窗外框
2. 在視窗內畫出客製作的視窗外框

這邊概述隱藏視窗外框的方法:
1. 編譯一個 DLL 檔(目的用來呼叫 WIN32 API),DLL 檔內提供一個隱藏視窗的函數 HideWindow() 如下:
int __declspec(dllexport) __stdcall HideWindow()
{
 //finde window
 HWND hWin =GetActiveWindow();
 if (hWin ==0)
  return 0;

 RECT rc;
 GetClientRect(hWin, &rc);

 long lStyle =GetWindowLong(hWin, GWL_STYLE);
 lStyle =lStyle & (~WS_CAPTION);
 SetWindowLong( hWin, GWL_STYLE, lStyle);
 
 SetWindowPos(hWin, NULL, 0, 0, rc.right, rc.bottom, SWP_NOMOVE);

 return 2;

}
2. 將編譯出來的 DLL 檔加至 Project 的 plugin 目錄下。

3. 在 Unity3D 裡建立一個 C# Script,並在裡面加入,其中 winframehidden 為 DLL 檔名:
[DllImport("winframehidden")]
private static extern int HideWindow();

然後在 Start() 函數內呼叫 HideWindow() 即可。