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

2009年9月4日 星期五

在C# Form中引用被封裝的資源檔(影像)

要把影像檔封裝到C# form的執行檔或函式庫裡面很容易
請參考在C#中的封裝資源檔
並請記得將建置動作(Build Action)設成內嵌資源(EmbeddedResource)
同時,依照放置位置的不同,引用方法也不同
我們將四張圖檔依照上面的方法分別放於四個位置
檔名位置
img.png直接置於該應用程式專案裡面
img_folder.png放在應用程式專案底下的folder內
img_dll.png直接置於參考的函式庫test_dll裡面
img_folder_dll.png放在參考的函式庫test_dll裡面的folder內

在C#裡面引用的話(i1-i4是PictureBox控制項物件)

/// get application assembly by file name
Assembly app = Assembly.LoadFrom("test_cs.exe");
Assembly dll = Assembly.LoadFrom("test_dll.dll");

/// image at project
i1.Image=Image.FromStream(
app.GetManifestResourceStream(
"test_cs.img.png"));

/// image in folder at project
i2.Image=Image.FromStream(
app.GetManifestResourceStream(
"test_cs.folder.img_folder.png"));

/// image at dll
i3.Image=Image.FromStream(
dll.GetManifestResourceStream(
"test_dll.img_dll.png"));

/// image in folder at dll
i4.Image=Image.FromStream(
dll.GetManifestResourceStream(
"test_dll.folder.img_folder_dll.png"));

注意,GetManifestResourceStream的參數字串
第一個部分不是檔名,而是命名空間(namespace)
命名空間.資料夾.檔名.附檔名

--
參考資料
Image Resources in WinForms and WPF
圖檔資源載入與不規則 Form 的製作

2009年8月19日 星期三

取得視窗關閉的理由 - CloseReason

在.net form預設的事件處理裡面有FormClosing

private void Form1_FormClosing(object sender,
FormClosingEventArgs e){...}

在視窗被關閉的時候會被啟動
e.CloseReason就是這個event發生的原因,常用如下
CloseReason說明
UserClosing使用者按下此form右上角的關閉按鈕
TaskManagerClosing用工作管理員強制關閉
WindowsShutDown關機的時候所觸發
UserClApplicationExitCallosing所從屬的應用程式被關閉時呼叫

此時可以針對不同的需求來做不同的處理
例如讓使用者做再一次的確認
並用e.Cancel抑制關閉事件的發生

private void Form1_FormClosing(object sender,
FormClosingEventArgs e)
{
/// if the close button in the title bar is clicked
if (e.CloseReason == CloseReason.UserClosing)
{
/// ask the user whether close or not
if (MessageBox.Show("Leave?", "warning",
MessageBoxButtons.YesNo) ==
DialogResult.No)
{
/// cancel the process of closing
e.Cancel = true;
}
}
}

但是到了WPF之後
Window的Closing事件和應用程式的關閉已經切開了
在Window的Closing事件中仍然可以被制止

private void Window_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
/// ask the user whether close or not
if (MessageBox.Show("Leave?", "warning",
MessageBoxButton.YesNo) ==
MessageBoxResult.No)
{
/// cancel the process of closing
e.Cancel = true;
}
}

但這時候已經沒有CloseReason可以選用了
因為單一視窗並不影響Application是否關閉
Application預設的關閉條件是最後的視窗被關閉
所以原先所提供的選項已經不再有意義

這時候如果仍然希望知道Application被關閉的原因
Application有提供SessionEnding事件
在Application的XAML裡面加上

<Application
...
SessionEnding="Application_SessionEnding">
<Application.Resources>
</Application.Resources>
</Application>

在程式碼中會看到

private void Application_SessionEnding(object sender,
SessionEndingCancelEventArgs e){...}

這時候可以從e.ReasonSessionEnding得到簡單的關閉原因

--
參考資料
WPF - Closing Application
表單右上角之關閉功能