Archive for the ‘东东博客’ Category

C#PropertyGrid多行编辑实现

星期四, 1 3 月, 2007

如要在PropertyGrid中显示多行编辑时需要重载UITypeEditor类并修改EditorAttribute属性。

1. 重载类MultilineTextEditor
public class MultilineTextEditor : UITypeEditor
{
private static ILog _log = LogManager.GetLogger(typeof(MultilineTextEditor));

public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}

public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
try
{
IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

if (svc != null)
{
if (value is string)
{
TextBox box = new TextBox();

box.AcceptsReturn = true;
box.Multiline = true;
box.Height = 120;
box.BorderStyle = BorderStyle.None;
box.Text = value as string;
svc.DropDownControl(box);

return box.Text;
}
}
}
catch (Exception ex)
{
if (_log.IsErrorEnabled)
{
_log.Error("MultilineTextEditor error: " + ex.Message);
}

return value;
}

return value;
}
}

2. 增加EditorAttribute属性
[DescriptionAttribute("The item description."),
EditorAttribute(typeof(MultilineTextEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string Description
{
get { return _data.Description; }
set { _data.Description = value; }
}

3. 将包含各个属性的类实例赋给PropertyGrid的SelectedObject属性,即可通过这个实现进行读写操作。

4. PropertyGrid 的部分外观特征
通过 HelpBackColor、HelpForeColor 和 HelpVisible 属性可以更改背景颜色、更改字体颜色或隐藏说明窗格。
通过 ToolbarVisible 属性可以隐藏工具栏,通过 BackColor 属性可以更改工具栏的颜色,通过 LargeButtons 属性可以显示大工具栏按钮。
使用 PropertySort 属性可以按字母顺序对属性进行排序和分类。
通过 BackColor 属性可以更改拆分器的颜色。
通过 LineColor 属性可以更改网格线和边框。

5. 部分属性的显示方式
DescriptionAttribute - 设置显示在属性下方说明帮助窗格中的属性文本。这是一种为活动属性(即具有焦点的属性)提供帮助文本的有效方法。
CategoryAttribute - 设置属性在网格中所属的类别。当您需要将属性按类别名称分组时,此特性非常有用。如果没有为属性指定类别,该属性将被分配给杂项类别。可以将此特性应用于所有属性。
BrowsableAttribute – 表示是否在网格中显示属性。此特性可用于在网格中隐藏属性。默认情况下,公共属性始终显示在网格中。
ReadOnlyAttribute – 表示属性是否为只读。此特性可用于禁止在网格中编辑属性。默认情况下,带有 get 和 set 访问函数的公共属性在网格中是可以编辑的。
DefaultValueAttribute – 表示属性的默认值。如果希望为属性提供默认值,然后确定该属性值是否与默认值相同,则可使用此特性。
DefaultPropertyAttribute – 表示类的默认属性。在网格中选择某个类时,将首先突出显示该类的默认属性。

C#程序启动欢迎窗体实现

星期一, 26 2 月, 2007

当程序在启动过程中需要花一些时间去加载资源时,我们希望程序能显示一个欢迎界面,能简单介绍软件功能的同时还能告知用户该程序还在加载中,使得用户体验更友好。
实现如下:

1. 添加欢迎界面的窗体(比如SlpashForm),做以下调整:
将FormBorderStyle属性设成None,即没有窗体边框
将StartPosition属性设成CenterScreen,即总是居中
将TopMost属性设成True,即总是在顶部
将UseWaitCursor属性设成Ture,即显示等待光标,让人感觉后台还在运行
增加一个PictureBox控件,与欢迎图片大小一致,窗体的大小也设成一致
增加一个ProgressBar控件,将Style设成Marquee,将MarqueeAnimationSpeed设成50

2. 主界面的构造函数改成以下代码:
// Create thread to show splash window
Thread showSplashThread = new Thread(new ThreadStart(ShowSplash));
showSplashThread.Start();

// Time consumed here
InitializeFrame(); // 把原来构造函数中的所有代码移到该函数中

// Abort show splash thread
showSplashThread.Abort();
showSplashThread.Join(); // Wait until the thread aborted
showSplashThread = null;

3. 显示SplashForm的线程函数
///

/// Thread to show the splash.
///

private void ShowSplash()
{
SplashForm sForm = null;
try
{
sForm = new SplashForm();
sForm.ShowDialog();
}
catch (ThreadAbortException e)
{
// Thread was aborted normally
if (_log.IsDebugEnabled)
{
_log.Debug("Splash window was aborted normally: " + e.Message);
}
}
finally
{
sForm = null;
}
}

4. 在主窗体的Load事件加激活自己的代码
SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle);

在使用SetForegroundWindow之前先声明一下
// Uses to active the exist window
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);

实例图:

C#单实例运行实现

星期一, 26 2 月, 2007

在某些情况我们要求应用程序只能运行一次,后运行的实例要把之前运行的程序激活并自己退出。
在网上搜索了一些实现并根据自己的理解重新整理得出下面的实现代码:

1. API函数的声明
// Uses to active the exist window
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);

[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

// 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized
private const int WS_SHOWNORMAL = 3;

2. 查找并激活已经存在的程序(仅应用于进程名相同的程序)
///

/// Finds the running instance.
///

/// true if exist a running instace, otherwise false
private static bool ExistRunningInstance()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName);

foreach (Process proc in procList)
{
// Found a running instance
if (proc.Id != currentProcess.Id)
{
// Active the running instance
ShowWindowAsync(proc.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(proc.MainWindowHandle);

return true;
}
}

return false;
}

3. 在Main函数入口判断
[STAThread]
static void Main()
{
// Control only one instance with the same process name can run
if (ExistRunningInstance())
{
Environment.Exit(1); // App is running, exit
}

// 程序真正运行的代码
}

C#多线程操作界面控件的解决方案

星期一, 26 2 月, 2007

C#2005后不再支持多线程直接访问界面的控件(界面创建线程与访问线程不是同一个线程),不过可以使用delegate来解决:

1. 声明一个delegate和定义一个delegate的实现函数
delegate void ShowProgressDelegate(int newPos);
private void ShowProgress(int newPos)
{
// 判断是否在线程中访问
if (!_progressBar.InvokeRequired)
{
// 不是的话直接操作控件
_progressBar.Value = newPos;
}
else
{
// 是的话启用delegate访问
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
// 如使用Invoke会等到函数调用结束,而BeginInvoke不会等待直接往后走
this.BeginInvoke(showProgress, new object[] { newPos });
}
}

2. 定义线程函数(在另一个线程中可以对界面控件进读操作)
private void ProgressStart()
{
while (true)
{
int newPos = _progressBar.Value + 10;

if (newPos > _progressBar.Maximum)
{
newPos = _progressBar.Minimum;
}
Trace.WriteLine(string.Format("Pos: {0}", newPos));

// 这里直接调用方法,由其内部自动判断是否启用delegate
ShowProgress(newPos);
Thread.Sleep(100);
}
}

3. 线程的启动和终止
private Thread _progressThread;
_progressThread = new Thread(new ThreadStart(ProgressStart));
// 可选,功用:即使该线程不结束,进程也可以结束
_progressThread.IsBackground = true;
_progressThread.Start();

_progressThread.Abort();
// 可选,功用:等到线程结束才继续
_progressThread.Join();
_progressThread = null;

这个春节过得真快,明天又上班了 :(

星期四, 22 2 月, 2007

总的来说这个春节过得马马虎虎,睡得是相当的舒服,吃来也比较腐败,不过就是人少没那么热闹。明天又该投入工作,同时期待着下一次的长假5.1,呵呵

金猪年初一天打了大半天的帝国II,眼都花了

星期日, 18 2 月, 2007

刚开始是LP大人和阿朱带上一个中级的电脑打我一个,虽说电脑只是中级的,但骚扰起人来确实难度,不用多想直接玩完。第二轮我也带个中级电脑,结果还是被电脑干扰,打乱了阵法,还是玩完。接着在我的强烈请求下大家都不带电脑,结果可想而知,才开始完两天的阿朱和不会使用快捷键的LP大人可不是我的敌手,爽了几把!

年夜饭不在状态,肚子装不下太多的酒

星期六, 17 2 月, 2007

今年过年在上海过,高中同学阿朱跟我们一起吃年夜饭。老婆大人弄的饭很不错,就是这肚子装不下酒,下午就犯困,不过把同学阿朱喝倒了,还是有点胜利的感觉。

好困呀,又该休息了

星期三, 14 2 月, 2007

今天刚给域名购买了空间,2年共计90大洋,网页空间50M,数据库空间20M,主机是上海电信接入的,感觉还可以。

用Google搜到Z-Blog ASP源码,用一下先,感觉是比较专业,赞扬一下。

由于还不很熟悉在日志中加链接之类的东西,加上整了一天了(老婆大人都怪我情人节没跟她多说几句了),先以最简单的方式发文,呵呵