Aaron Liu的部落格,紀錄我的生活點點滴滴

顯示具有 Developer 標籤的文章。 顯示所有文章
顯示具有 Developer 標籤的文章。 顯示所有文章

Bubble Breaker小遊戲

| 2009年2月24日 星期二
家中女王迷上了小弟手機上Windows Mobile內建的Bubble Breaker小遊戲,為了將手機從女王手中解放出來,只好寫一個PC版的給他玩。



因為沒有bubble的圖,所以bubble都長成方塊的樣子。

基本上遊戲的計分方法是:
消去n個方塊,得n*(n-1)分
若n>10則分數x3
最後消去所有方塊,得額外的1000分
最後消去剩下不到5個方塊,得額外的500分
最後消去剩下不到10個方塊,得額外的100分


為何女王的紀錄可以那麼高分!告訴我秘訣吧!

最後,請享用:
http://www.badongo.com/file/13537956


PS. 如果出現「應用程式正常初始失敗」訊息,請安裝.Net 2.0環境


繼續閱讀...

Qt初心者之路::Hello World篇

| 2009年2月11日 星期三
這篇將以一個.Net慣用者的身份來探索Qt的世界。

不免俗地,從Hello World開始吧!



從Eclipse的File選單可以開啟一個Qt Gui Project,我將專案命名為「FirstQt」,選擇存放目錄以後,就可以開始開發了。如上圖,Eclipse和Visual Studio看起來不大像,但其實功能大同小異,左側欄的「C/C++ Projects」相當於Visual Studio的方案總管,「Qt C++ Widget Box」則相當於工具箱,在Qt的世界,Widget就相當於.Net講的Control。



畫面的中間一看便知是設計Windows Form的地方,可以將左邊的Widget拖到Form裡面放。對於Form的編輯,Eclipse能夠過雙擊Widget自動新增事件處理method,換句話說,它不像Visual Studio可以再拖好的Button上面點兩下,就自動跳到Button_Click的程式馬編輯器。如果要將事件處理交由系統預設好的一些事件處理函數處理(例如hide, repaint等),可以使用下方的Qt C++ Signal Slot Editor,如果要自己寫處理函數,則只要宣告為slot並按照特定的規則命名即可,後面會進一步說明。



至於Widget的屬性設定,可以在右側的Qt C++欄找到,Eclipes還會用顏色分類,就甘心ㄟ!



接下來開始建立一個Hello World程式,首先在Form裡面拖進一個Lable和一個Button,分將objectName改為「labTest」和「butTest」,並編輯一下text屬性,就成了下面的樣子。



接著我們要新增butTest按鈕的click事件。Qt將Event稱為Signal,Event Handler則稱為Slot,要新增一個signal和slot的對應,最簡單的方法就是將一個函數宣告為slot並且用特定的方式去命名。

首先,在宣告檔firstqt.h裡面,新增一段slot的宣告:

private slots:
void on_butTest_clicked();


此處必須要注意,slot函數的名稱,必須要遵照「on_發出事件的Widget名稱_signal名稱」來命名,Qt才會自動將此函數對應到該事件處理。

接著在FirstQt.cpp裡面實做剛剛宣告的on_butTest_clicked函數:

void FirstQt::on_butTest_clicked()
{
ui.labTest->setText(" Hello World!");
return;
}


這裡值得注意的是,Widget並不是像.net一樣直接宣告在Form(FirstQtClass物件)裡面,而是在ui物件裡面,我們可以透過ui物件去存取到其他的Widget。

如此,大功告成!按下Run即可執行程式了!




繼續閱讀...

Qt初心者之路::IDE環境安裝篇

| 2009年2月10日 星期二
心血來潮,想說用微軟的工具寫程式已經七八年了,也該換換跑道接觸一下其他的平台。

但是,要玩什麼好呢?

我的想法是:
1. 不想碰一個完全不熟悉的語言,太累了, 於是Ruby、Python被打槍
2. 最近也想碰Embeeded System,非微軟又有潛力在Embeeded環境跑的,不外乎GTK+和Qt了
3. 要有能在XP上跑的IED,這樣一來學習曲線不會太痛苦,二來我也沒空弄一台Linux來玩,於是乎Qt出線了




基本上Qt的開發要安裝MinGW(Compiler)、Qt(Library)和IDE環境,而IDE環境一般來說是Eclipse + Qt Eclipse Integration套件,不過Qt官方最近新出了一套Qt Creator,雖然目前只出了rc版,但是有「一次安裝包」(Package includes a complete Windows developer environment with MinGW and Qt 4.4.3 built with MinGW. No other download required.)。為了圖方便就選擇了他。


Qt Creator 0.9.2 (RC1)可以在這裡取得

不過,不知道是Qt Creator和我的NB犯衝還是rc版真的還有許多缺陷,這個開發環境在我的電腦上一直當,動不動就耍自閉不理人,不然就是視窗突然消失,實在是沒耐心跟它耗,於是轉而投向Eclipse。

Eclipse可以選擇「Eclipse IDE for C/C++ Developers」版本,此版會預設裝好Eclipse C/C++ Development Tooling - CDT,如果用沒裝CDT的Java開發版本,是不會work的。

基本上Eclipse如果下載的是的C/C++ Developers版,那麼安裝手續只要解壓縮就好。接著必須安裝Qt Eclipse Integration for C++,安裝過程中會詢問Qt和MinGW的bin路徑在哪裡,以我的例子來說,由於這兩個東西都是在裝Qt Creator時順便裝的,因此得選擇「D:\Qt\QtCreator\qt\bin」和「D:\Qt\QtCreator\mingw\bin」。



至此,Qt基本的開發環境就安裝完成了!下次再來寫Hello World...

繼續閱讀...

XDHome 0.6.2 HTPC播放軟體 小小改版

| 2009年1月18日 星期日
這次推出一個小小改版,解決檔案目錄不會更新的問題,這一版的程式,每次隱藏又重啟之後,都會去更新檔案清單,這樣就不會看到幽靈檔案了。

下載XDHome 0.6.2版



繼續閱讀...

[C#]全域鍵盤事件攔截(Low Level Keyboard Hook)

| 2009年1月11日 星期日
寫XDHome的時候其實只有兩個技術問題需要突破,一個是上次提過的影片播放,另一個就是要如何在視窗不被focus的時候也能夠抓到鍵盤。

基本上要解決這個問題,必須要呼叫Windows API去設定所謂的Low Level Hook,網路上有一些範例可以抓,基本上我參考了George Mamaladze和Huan Lin兩人的著作,將程式改為指針對Keyboard的KeyDown事件的版本,程式碼如下:

Low Level Keyboard Hook服務程式
此段程式碼提供兩個static KeyDown Event供客戶端程式碼新增Even Handler

// Low Level Keyboard Hook
public class KeyboardHook
{

// System Code: Low Level Keyboard Hook
private const int WH_KEYBOARD_LL = 13;

// System Event Code: Key Down Event
private const int WM_KEYDOWN = 0x100;

// System Event Code: System Key Down Event
private const int WM_SYSKEYDOWN = 0x104;

// Stores the handle to the Keyboard hook procedure.
private static int s_KeyboardHookHandle;

//是否只由這個Global Hook抓取鍵盤事件
public static bool globalControlOnly = false;

//Private KeyDown Event, 與GlobalKeyDown配合使用
private static event KeyEventHandler _globalKeyDown;

// Public KeyDown Event
// 每次只能一個Event Handler處理這個Event
// 加入和解除EventHandler時會自動安裝和解除Hook
public static event KeyEventHandler GlobalKeyDown
{
add
{
KeyboardHook.HookKeyboard();
KeyboardHook._globalKeyDown += value;
}
remove
{
KeyboardHook._globalKeyDown -= value;
KeyboardHook.UnhookKeyboard();
}
}




// 當hook抓到key event時的處理程序
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

// Hook handle
private static int m_HookHandle = 0;

// Keyboard Hook函式指標
private static HookProc m_KbdHookProc;

// WinAPI 取得Module Handle
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

// WinAPI 加入Hook
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);


// WinAPI 解除Hook
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);


// WinAPI 將Event傳給下一個Hook,如不執行此項,則只有這個Hook會被執行
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);


private static void HookKeyboard()
{
if (m_HookHandle == 0)
{

KeyboardHook.s_KeyboardHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, m_KbdHookProc,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);

using (Process curProcess = Process.GetCurrentProcess())
{
using (ProcessModule curModule = curProcess.MainModule)
{
m_KbdHookProc = new HookProc(KeyboardHookProc);
m_HookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, m_KbdHookProc, GetModuleHandle(curModule.ModuleName), 0);
}
}

if (m_HookHandle == 0)
{
throw new Exception("Install Global Keyboard Hook Faild.");
}

}
}


private static void UnhookKeyboard()
{

if (m_HookHandle != 0)
{
bool ret = UnhookWindowsHookEx(m_HookHandle);
if (ret)
{
m_HookHandle = 0;
}
else
{
throw new Exception("Uninstall Global Keyboard Hook Faild.");
}

}

}





private static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool handled = false;

if(nCode >= 0)
{

if ((int)wParam == WM_KEYDOWN || (int)wParam == WM_SYSKEYDOWN)
{
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode;
KeyEventArgs e = new KeyEventArgs(keyData);

if (KeyboardHook.globalControlOnly)
{
e.Handled = true;
}
else
{
e.Handled = false;
}

_globalKeyDown.Invoke(null, e);

handled = e.Handled;
}

}


if (KeyboardHook.globalControlOnly) return -1;

return CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam);


}



[StructLayout(LayoutKind.Sequential)]
private struct KeyboardHookStruct
{
///
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
///

public int VirtualKeyCode;
///
/// Specifies a hardware scan code for the key.
///

public int ScanCode;
///
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
///

public int Flags;
///
/// Specifies the Time stamp for this message.
///

public int Time;
///
/// Specifies extra information associated with the message.
///

public int ExtraInfo;
}

}


客戶端程式碼,Handel static的全域KeyDown Event

private void KeyboardHook_KeyDown(object sender, KeyEventArgs e)
{
string key = e.KeyCode.ToString(); //取得KeyCode字串
//TODO: 加入處理KeyDown事件的程式
}


要加入全域事件時

KeyboardHook.globalControlOnly = true; //只有Global KeyDown會起作用,其他程式不能攔截鍵盤事件
KeyboardHook.GlobalKeyDown += KeyboardHook_KeyDown;


要取消全域事件處理時

KeyboardHook.GlobalKeyDown -= KeyboardHook_KeyDown;


繼續閱讀...

XDHome 0.6.1 HTPC播放軟體 小改版釋出

|
下載XDHome 0.6.1

XDHome 0.6.1版釋出,這次除了修正一些bug之外,還將原始檔一併公布。

修正: Pause鍵按第二次時不會恢復播放狀態

目前bin和原始檔都公布在SourceForge上面,原始碼以LGPL方式授權,歡迎有興趣的朋友一起研究。

繼續閱讀...

XDHome 0.6 電視專用播放器

| 2009年1月5日 星期一
下載XDHome 0.6版

這個版本較前一版(0.1)有許多的改善,我還是重新介紹一下好了。

XDHome是一個可以完全用遙控器/鍵盤操作的影片播放器,專門用來將電腦內的影片在電視上播放用的,所以它可以:
  1. 以大字體瀏覽檔案,讓人在電視上也看得清楚檔名。
  2. 自行設定所有功能與鍵盤的對應,讓任何遙控器都可以配合使用。
  3. 播放影片檔,只要有裝正確的CODEC就可以播出,同時也支援外掛字幕。



0.6版較0.1版更新的功能有:
  1. 有完整的檔案系統瀏覽功能
  2. 新增自訂按鍵功能
  3. 新增捷徑功能
  4. 影片播放改用DirectShowNet,沒有相容問題
  5. 全新的Keyboard Hook,較前版穩定

使用的時候請注意:
  1. XDHome開啟時會攔截所有的鍵盤事件,其他程式會抓不到鍵盤,但少數系統鍵還是可以運作(例如Ctrl+Alt+Del)
  2. XDHome是以C#基於.Net 2.0和DirectShowNet 2.0開發的,必須要安裝.Net Framework 2.0和DirectX 9以上版本才能執行。
  3. 目前只能播放影片檔(avi、wmv、rm、rmvb、mkv),但是DVD還不行。
臭蟲還沒完全抓完,但應該還勘用,有用到什麼問題的話,請寫在回應裡面。

繼續閱讀...

[C#]使用DirectShowNet播放影片檔

| 2009年1月1日 星期四
DirectShowNet是SourceForge上面的開放源碼函示庫,基本上它將DirectShow 9包裝成.Net 2.0的函示庫,使用上其實有點複雜,要用的話,請先下載DirectShowNet 2.0。程式碼是按照DirectShowNet的範例改出來的,案例可以從這裡下載。

我將一些播放影片檔的基本功能功能寫成含註解的程式碼如下:


/// <summary>
/// 播放狀態
/// </summary>
public enum PlayState
{
Stopped, //視訊停止
Paused, //視訊暫停
Playing, //視訊播放中
Init //尚未開啟任何影片檔
};

/// <summary>
/// 播放Video物件
/// </summary>
public class Video
{

private const int WMGraphNotify = 0x0400 + 13;
public const int VolumeFull = 0;
public const int VolumeSilence = -10000;

private DirectShowLib.IGraphBuilder graphBuilder = null;
private DirectShowLib.IMediaControl mediaControl = null;
private DirectShowLib.IMediaEventEx mediaEventEx = null;
private DirectShowLib.IVideoWindow videoWindow = null;
private DirectShowLib.IBasicAudio basicAudio = null;
private DirectShowLib.IBasicVideo basicVideo = null;
private DirectShowLib.IMediaSeeking mediaSeeking = null;
private DirectShowLib.IMediaPosition mediaPosition = null;
private DirectShowLib.IVideoFrameStep frameStep = null;

private string filePath = string.Empty;
private bool _FullScreen = false;
private int _Volume = VolumeFull;
public PlayState State = PlayState.Init;
private double currentPlaybackRate = 1.0;

private Size _size = new Size(0, 0);
private IntPtr hDrain = IntPtr.Zero;

#if DEBUG
private DsROTEntry rot = null;
#endif

/// <summary>
/// 裝載視訊物件的Container
/// </summary>
public Control Owner;


/// <summary>
/// 是否全螢幕模式
/// </summary>
public bool FullScreen
{
get
{
return _FullScreen;
}
set
{
if (this.State == PlayState.Init)
{
throw new Exception("No video file has been opened");
}

if (value != _FullScreen)
{
int hr = 0;
OABool lMode;

if (value)
{
//設定為全螢幕
hr = this.videoWindow.get_MessageDrain(out hDrain);
DsError.ThrowExceptionForHR(hr);
hr = this.videoWindow.put_MessageDrain(Owner.Handle);
DsError.ThrowExceptionForHR(hr);

lMode = OABool.True;
hr = this.videoWindow.put_FullScreenMode(lMode);
DsError.ThrowExceptionForHR(hr);
}
else
{
//回復視窗模式
lMode = OABool.False;
hr = this.videoWindow.put_FullScreenMode(lMode);
DsError.ThrowExceptionForHR(hr);

hr = this.videoWindow.put_MessageDrain(hDrain);
DsError.ThrowExceptionForHR(hr);
hr = this.videoWindow.SetWindowForeground(OABool.True);
DsError.ThrowExceptionForHR(hr);
}
}

this._FullScreen = value;

}

}

/// <summary>
/// 取得/設定寬度
/// </summary>
public int Width
{
get
{
return _size.Width;
}
set
{
if (this.State == PlayState.Init)
{
throw new Exception("No video file has been opened");
}

int hr = 0;
this.Owner.Width = value;
hr = this.videoWindow.SetWindowPosition(0, 0, value, _size.Height);
DsError.ThrowExceptionForHR(hr);
this._size.Height = value;
}
}

/// <summary>
/// 取得/設定高度
/// </summary>
public int Height
{
get
{
return _size.Height;
}
set
{
if (this.State == PlayState.Init)
{
throw new Exception("No video file has been opened");
}

int hr = 0;
this.Owner.Height = value;
hr = this.videoWindow.SetWindowPosition(0, 0, _size.Width, value);
DsError.ThrowExceptionForHR(hr);
this._size.Height = value;
}
}

/// <summary>
/// 取得目前影片的長度(秒數)
/// </summary>
public long Duration
{
get
{
if (State == PlayState.Init)
{
return 0;
}
else
{
int hr = 0;
long dur;
hr = this.mediaSeeking.GetDuration(out dur);
DsError.ThrowExceptionForHR(hr);

TimeSpan t = new TimeSpan(dur);
return (long)t.TotalSeconds;
}
}
}

/// <summary>
/// 目前的位置(秒數)
/// </summary>
public long Position
{
get
{
if (State == PlayState.Init)
{
return 0;
}
else
{
int hr = 0;
long pos, stop;
hr = this.mediaSeeking.GetPositions(out pos, out stop);

TimeSpan t = new TimeSpan(pos);


return (long)t.TotalSeconds;
}
}

set
{
if (this.State == PlayState.Init)
{
throw new Exception("No video file has been opened");
}

if (Position < 0 || Position > Duration)
{
throw new Exception("Position out of range");
}

int hr = 0;
TimeSpan t = new TimeSpan(0, 0,(int)value);

DsLong newPosition = new DsLong(t.Ticks);
hr = this.mediaSeeking.SetPositions(newPosition, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
}
}


/// <summary>
/// 目前的音量大小 0~100
/// </summary>
public int Volume
{
get
{

return this._Volume / 100 + 100;
}
set
{
if (value > 100 || value < 0)
{
throw new Exception("Volume must between 0 to 100");
}

int hr = 0;
this._Volume = (value - 100) * 100;
hr = this.basicAudio.put_Volume(this._Volume);
}
}




/// <summary>
/// 初始化Video物件
/// </summary>
/// <param name="owner">Video附著的Container 通常是一個Pannel或Form</param>
public Video(ref Control owner)
{
this.Owner = owner;
}

/// <summary>
/// 開啟視訊檔
/// </summary>
/// <param name="filePath">視訊檔案路徑</param>
/// <param name="autoPlay">開啟後是否自動播放</param>
public void Open(string filePath, bool autoPlay)
{
int hr = 0;

if (!System.IO.File.Exists(filePath))
{
throw new Exception("File " + filePath + "Not Found!");
}


if (State != PlayState.Init)
{
CloseVideo();
}


//取得檔案stream
this.graphBuilder = (DirectShowLib.IGraphBuilder)new FilterGraph();
hr = this.graphBuilder.RenderFile(filePath, null);
DsError.ThrowExceptionForHR(hr);


//Get DirectShow Control interfaces
this.mediaControl = (DirectShowLib.IMediaControl)this.graphBuilder;
this.mediaEventEx = (DirectShowLib.IMediaEventEx)this.graphBuilder;
this.mediaSeeking = (DirectShowLib.IMediaSeeking)this.graphBuilder;
this.mediaPosition = (DirectShowLib.IMediaPosition)this.graphBuilder;

this.videoWindow = this.graphBuilder as DirectShowLib.IVideoWindow;
this.basicVideo = this.graphBuilder as DirectShowLib.IBasicVideo;
this.basicAudio = this.graphBuilder as DirectShowLib.IBasicAudio;

if (!IsVideo())
{
throw new Exception("The File Is Not A Video File Or The Codec Is Unsupported!");
}

//Set the playback event handle object
//hr = this.mediaEventEx.SetNotifyWindow(this.Owner.Handle, WMGraphNotify, IntPtr.Zero);
//DsError.ThrowExceptionForHR(hr);

//Set the video owner object to contain the vidwo window
hr = this.videoWindow.put_Owner(this.Owner.Handle);
DsError.ThrowExceptionForHR(hr);

//Set video window layout
hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
DsError.ThrowExceptionForHR(hr);


//Get vedio size
int lHeight, lWidth;
hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight);
DsError.ThrowExceptionForHR(hr);

//set owner object size as video size
this.Owner.Width = lWidth;
this.Owner.Height = lHeight;
this._size.Width = lWidth;
this._size.Height = lHeight;

hr = this.videoWindow.SetWindowPosition(0, 0, lWidth, lHeight);
DsError.ThrowExceptionForHR(hr);


GetFrameStepInterface();


this._FullScreen = false;
this.currentPlaybackRate = 1.0;

this.State = PlayState.Stopped;
this.filePath = filePath;

if (autoPlay)
{
Play();
}


}


/// <summary>
/// 播放視訊檔
/// </summary>
public void Play()
{
if (State == PlayState.Stopped || State == PlayState.Paused)
{
int hr = 0;
hr = this.mediaControl.Run();
DsError.ThrowExceptionForHR(hr);

this.State = PlayState.Playing;
}


}

/// <summary>
/// 停止播放視訊檔
/// </summary>
public void Stop()
{
if (State == PlayState.Playing || State == PlayState.Paused)
{
int hr = 0;

//停止播放
hr = this.mediaControl.Stop();
DsError.ThrowExceptionForHR(hr);

//回到第一個影格
DsLong pos = new DsLong(0);
hr = this.mediaSeeking.SetPositions(pos, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
//顯示第一個影格
hr = this.mediaControl.Pause();

this.State = PlayState.Stopped;
}
}


/// <summary>
/// 停止播放視訊檔
/// </summary>
public void Pause()
{
if (State == PlayState.Playing)
{
int hr = 0;
hr = this.mediaControl.Pause();
DsError.ThrowExceptionForHR(hr);

this.State = PlayState.Paused;
}
}

/// <summary>
/// 前進
/// </summary>
/// <param name="second">前進的秒數</param>
public void Forward(int second)
{
if (Position + second < Duration)
{
Position += second;
}
else
{
Position = Duration;
}

}

/// <summary>
/// 倒退
/// </summary>
/// <param name="second">倒退的秒數</param>
public void Backward(int second)
{
if (Position - second > 0)
{
Position -= second;
}
else
{
Position = 0;
}

}


/// <summary>
/// 視訊檔案是否是一個被支援的視訊檔?
/// </summary>
/// <returns>true = 是; false = 否</returns>
private bool IsVideo()
{
int hr = 0;
OABool lVisible;
bool result = true;

if ((this.videoWindow == null) || (this.basicVideo == null))
{
//是一個Audio檔(沒有視訊,只有音訊)
result = false;
}


hr = this.videoWindow.get_Visible(out lVisible);
if (hr < 0)
{
// 視訊檔使用的Codec不被支援的或根本不是視訊檔
if (hr == unchecked((int)0x80004002)) //E_NOINTERFACE
{
result = false;
}
else
DsError.ThrowExceptionForHR(hr);
}

return result;
}


/// <summary>
/// 取得格放時要用的IVideoFrameStep介面
/// </summary>
/// <returns>true = 可以取得格放介面 false = 無法取得格放介面</returns>
private bool GetFrameStepInterface()
{
int hr = 0;

DirectShowLib.IVideoFrameStep frameStepTest = null;

// Get the frame step interface, if supported
frameStepTest = (DirectShowLib.IVideoFrameStep)this.graphBuilder;

// Check if this decoder can step
hr = frameStepTest.CanStep(0, null);
if (hr == 0)
{
this.frameStep = frameStepTest;
return true;
}
else
{
this.frameStep = null;
return false;
}
}



/// <summary>
/// 關閉視訊檔
/// </summary>
public void CloseVideo()
{
int hr = 0;

//停止播放
if (this.mediaControl != null)
hr = this.mediaControl.Stop();

// Clear global flags
this.State = PlayState.Stopped;
this.FullScreen = false;

//關閉DirectShow Control Interfece
CloseInterfaces();


this.filePath = string.Empty;
this.State = PlayState.Init;
}

/// <summary>
/// 關閉DirectShow的Control Interface
/// </summary>
private void CloseInterfaces()
{
int hr = 0;

try
{
lock (this)
{
// Relinquish ownership (IMPORTANT!) after hiding video window

if (this.videoWindow != null)
{
hr = this.videoWindow.put_Visible(OABool.False);
DsError.ThrowExceptionForHR(hr);
hr = this.videoWindow.put_Owner(IntPtr.Zero);
DsError.ThrowExceptionForHR(hr);
}
if (this.mediaEventEx != null)
{
hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero);
DsError.ThrowExceptionForHR(hr);
}

#if DEBUG
if (rot != null)
{
rot.Dispose();
rot = null;
}
#endif
// Release and zero DirectShow interfaces
if (this.mediaEventEx != null)
this.mediaEventEx = null;
if (this.mediaSeeking != null)
this.mediaSeeking = null;
if (this.mediaPosition != null)
this.mediaPosition = null;
if (this.mediaControl != null)
this.mediaControl = null;
if (this.basicAudio != null)
this.basicAudio = null;
if (this.basicVideo != null)
this.basicVideo = null;
if (this.frameStep != null)
this.frameStep = null;
if (this.graphBuilder != null)
Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;

GC.Collect();
}
}
catch(Exception ex)
{
throw new Exception("Video close faild:\r\n" + ex.Message);
}
}






}

根據我自己的實測,這樣寫出來的播放器,只要Codec有裝幾乎什麼檔都可以播,包含AVI、WMV、MKV都已經測過OK,連str外掛字幕檔都可以顯示,還不賴。

繼續閱讀...

尋找.Net影片播放方法的心路歷程

| 2008年12月29日 星期一
我是個C#的慣用者,最近在寫XDHome的過程中,發現用C#播放影片是件挺麻煩的事情。

首先,.Net雖然都出到3.5了,但是VB6就有的Multi Media Control卻從.Net 1.x就不見到現在,不知道微軟什麼時候才會把這個控制項找回來。至於Windows Media Play的嵌入式控制項,雖然還滿方便的,但我個人就是不喜歡WMP才要自己寫,所以就免了吧!

其次,微軟在DirectX 9時代有出過Managed DirectX,在該版本的Microsoft.DirectX.AudioVideoPlayback下面有個Vedio物件,這個東西可以說是有史以來我用過最好用的Vedio播放元件,不但介面簡單,而且看有str外掛字幕檔的影片時,還會自動叫vobsub,實在太讚了!不過很可惜,微軟的Manage DirectX只此一版,而且是.Net 1.1作的,用Visual Studio 2005或2008開發時,會有Loader Lock Exception,雖然可以用一些技巧去避免,但是在部署時一定會比較麻煩。至於Managed DirectX後面衍生出來的XNA則是完完全全地把Vedio物件拿掉了,天知道微軟什麼時候會再放回去。

最後我動腦筋到SourceForge上面的「DirectShowNet Library」,這個專案很忠實地把DirectShow包裝成.Net 2.0的物件,因此操作起來就跟直接用DirectShow一樣麻煩,而且裡面夾雜了很多C++式的例外語法,讓C#整個變得有點怪。但是沒魚蝦也好,湊合著用吧,有空再來寫範例碼。

繼續閱讀...

XDHome 0.1 Alpha版 給電視遙控用的輕量播放器

| 2008年12月24日 星期三
下載XDHome 0.1

XDHome是一個完全由「鍵盤」控制的影片檔播放器,他支援目錄瀏覽和基本的影片迴放功能,包含快轉、倒轉、全螢幕、暫停等等,或許這些看來很陽春,但是他的SIZE也很小。

XDHome的設計是為了讓電腦裡的影片可在電視上面播放,因此「遙控器」的支援是很重要的,大部分的電腦用遙控器都可以被當作「鍵盤」來用,因此XDHome被設計為完全可以由鍵盤控制的播放器。每個功能在鍵盤上面的對應,都被寫在config檔裡面,使用者可以自己用記事本更改。

目前這個程式被裝在我的老HP NC4000筆記本上,接上37吋大電視,做Full HD的輸出,表現還差強人意。

就技術上來說,XDHome是用Managed DirectX寫的一個播放器,基本上在.Net 2.0上面運行,這樣的搭配也許很怪,下一個版本或許會改用XNA。目前想到未完成的功能還有:
1. DVD播放
2. 鍵盤對應表介面
3. 獨立的鍵盤對應檔(目前用App.config)

有空再來寫吧

繼續閱讀...