此FAQ的内容,一部分来自 net精简框架新闻组 (microsoft.public.dotnet.framework.compactframework)张贴和回答的问题。.net精简框架开发小组感谢每一位参与新闻组的人事,感谢他们对FAQ编写的积极参与和对FAQ的投稿。
要申请添加FAQ项目,请发邮件到 netcffaq@microsoft.com.
1. 开发
1.1. 什么是微软 .net精简框架?2. 图形
1.2. 我需要什么工具才能开发.net精简框架的应用?
1.3. 哪里可以下载最新的工具和相关软件?
1.4. .net精简框架支持些什么设备?
1.5. .net精简框架以后将支持什么设备?
1.6. 调试程序时为什么会出现“与模拟器建立连接失败”的错误(刚开始执行程序的时候)?
1.7. .net框架和.net精简框架之间有什么区别?
1.8. .net精简框架的补丁有什么改进?
1.9. Poclet PC上的.net精简框架开发和Windows CE .NET上的.net精简框架开发有什么不同?
1.10. 哪里有更多的关于建立.net精简框架上的应用程序的信息?
1.11. .net精简框架的文档在哪里?
1.12. 怎样设置才不会在每次调试的时候把所涉及的文件都拷贝到设备上?
1.13. 怎样设置模拟器的属性?
1.14. 怎么调试.net精简框架的应用程序?
1.15. 怎样开始使用Visual Basic .NET开发.net精简框架的程序?
1.16. 怎样才能把.net精简框架安装到装配集中(GAC)?
1.17. 当从Visual Studio .NET 2003中发布程序到设备上的时候,怎样处理"Sharing Violation"?
1.18. 什么是common language runtime (CLR)?
1.19. 什么是Global Assembly Cache (GAC)?
1.20. 在.net精简框架下内存管理是怎样的?
1.21. 当我的网络协议数超过50个的时候,为什么不能向发布程序?
1.22. 为什么会有跨平台代码?
1.23. 这些ARM指令代表什么?
1.24. 怎样写注册表?
1.25. How can I prevent .CAB files from being deleted after installation?
1.26. How can I determine the version of the .NET Compact Framework that is installed on a device?
1.27. How do I copy files to the emulator?
1.28. Why does installation of the PocketPC 2002 SDK fail?
1.29. How do I debug a Web service consumed by a Smart Device application?
1.30. What is the footprint of the .NET Compact Framework?
1.31. How do I include imgdecmp.dll in an emulator image?
1.32. How do I programmatically replace Assemblies in the Global Assembly Cache (GAC)?
1.33. How can I display Pocket PC applications on my desktop or laptop without needing any device side configuration?
1.34. How can I allow Activesync to connect to an Emulator session from Visual Studio .NET 2003?
1.35. How can I copy files to the device currently connected to desktop ActiveSync?
1.36. How can I stress test user input?
1.37. Where can I get a UI version of the Platform Builder Target Control Window?
1.38. Where can I get a Command shell for Pocket PC 2003 devices?
1.39. How can I get detailed information about currently running processes?
1.40. How can I remotely start an application on a Pocket PC from my desktop?
1.41. Why can't I load different assemblies with the same name?
1.42. How can I force Visual Studio .NET 2003 to connect to newer versions of the Pocket PC 2003 emulator?
1.43. Why don't my custom controls show up properly in the toolbox?
2.1. 怎样建立一个图形对象?3. 发布
2.2. 怎样优化GDI+?
2.3. 怎样在窗体上画一个图案?
2.4. 怎样画一个带有透明色的图案?
2.5. 为什么从TextBox上调用CreateGraphics会失败?
2.6. 怎样获得屏幕上文字的大小?
2.7. Can I set the width of a pen?
2.8. How do I zoom an image?
2.9. Why can't I load an image?
3.1. 怎样建立一个PocketPC的设置程序?4. 图形用户界面(GUI): 窗体
3.2. 哪个发布包可以包括在我的安装程序中?
3.3. 怎样可以建立一个不需要.net框架的安装程序?
3.4. 怎样建立不受PocketPC系统约束的CAB安装文件?
3.5. 为什么不同的处理器会有不同的CAB安装文件?
3.6. How do I create a desktop installer that detects the presence of the .NET Compact Framework on the target device and installs it if necessary?
3.7. How do I deploy a .NET Compact Framework Service Pack to the emulator?
3.8. How do I include SQL Server CE with my application installation?
3.9. How do I use GAPI to create a graphics engine?
4.1. 怎样建立一个全屏的窗体?5. 图形用户界面 (GUI): 通用
4.2. 什么时候用窗体的构造器?什么时候用窗体的Load事件?
4.3. 怎样把最小化按钮换成关闭按钮?
4.4. 怎样在.net精简框架上建立多窗体系统结构?
4.5. 怎样提高.net精简框架应用程序的载入速度?
4.6. 运行时怎样修改窗体的风格?
4.7. 怎样滚动窗体的内容?
4.8. 怎样制作一个浮动的窗体?好象所有的窗体总是全屏状态的。
4.9. 怎样强迫一个窗体变成最小化?
4.10. 我有一个包含很多控件的智能设备窗体,为什么运行的时候出现"NotSupportedException"错误?
4.11. 哪个是正确关闭窗体的方法:Appplication.Exit 还是 Form.Close ?
4.12. Why does showing a MessageBox on Windows Mobile 2003 for Smartphone with the Abort, Retry, and Fail set of buttons or the Yes, No, Cancel set of buttons, or the third button as the default button result in a NotSupportedException?
4.13 How do I get an icon in the Pocket PC Start Menu Most Recently Used (MRU) List?
4.14 How do I center a Form on the screen?
4.15 Why can't I show a Form that has been closed?
4.16 How can I enable multiple instances of an application?
5.1. 怎样建立一个带有图形或支持多行的按钮?6. 与本地代码(Native Code)协同工作
5.2. TextBox.AcceptsReturn在.net精简框架下是怎样工作的?
5.3. 当数据载入ComboBox的时候,为什么SelectedIndexChanged事件没有被触发?
5.4. Show和ShowDialog有什么不同?
5.5. 为什么我不能建立右键菜单分离器?(separator)
5.6. 运行时把ImageList赋给ToolBar时,为什么图象不出现?
5.7. 怎样把光标设置成等待状态?
5.8. 如何在菜单项中显示符号:&?
5.9. 如何制作基于.net精简框架的动画控件?
5.10. 如何在.net精简框架上制作自定义控件?
5.11. 如何制作基于.net精简框架的带图片的按钮?
5.12. 如何使用.net精简框架下的MessageWindow类库?
5.13. 如何向DataGrid中添加行和列?
5.14. 如何实现DataGrid的编辑?
5.15. 怎样设置DataGrid的DataSource?
5.16. 怎样对DataGrid的列排序?
5.17. 怎样对ListView中的内容排序?
5.18. 如何使用 输入板(SIP)控件?
5.19. 如何自定义事件?
5.20. 如何做一个 owner-drawn List Box?
5.21. 如何做一个多选框判断真假?
5.22. 设置InputPanel.Enabled = true的时候为什么出现异常?
5.23. 为什么自定义控件不会自动继承父类的字体?
5.24. 为什么当输入字符时,NumericUpDown 和 DomainUpDown 控件不会引发 ValueChanged 和 SelectedItemChanged 事件?
5.25. 为什么NumericUpDown控件增长的值不是设置好的值?
5.26. 为什么StatusBar不能放在窗体的任意位置?一定要在底部?
5.27. 为什么我的控件自动继承了父控件的背景色?
5.28. 为什么NumericUpDown控件能接受decimal类型的值,但不会显示大于2^16的值?
5.29. 为什么不能在DomainUpDown 中输入文字,而要选择?
5.30. 为什么OpenFileDialog被限制在"My Documents" 文件夹中?
5.31. How can I activate the SIP (InputPanel) without a menu?
5.32. How do I add a subnode to every node in a TreeView?
5.33. How do I determine the number of rows or columns in a DataGrid?
5.34. How do I create a owner drawn Listbox?
5.35. How can I implement Control.GetNextControl under the .NET Compact Framework?
5.36. How do I get notified when the user clicks on a treeview node?
5.37. How do I set the title of a fullscreen multiline edit control window?
5.38. Why don' I see the validItem selected when I set ComboBox.SelectedValue to validItemInCollection?
5.39. How do I detect the location where a 'tap & hold' occurred to bring up a context menu on my custom control?
5.40. Why doesn't the scrollbar value ever get set to the maximum value?
5.41. How do I tab out of a custom control to the previous control?
5.42. How do I add Toolbar buttons with Transparency?
6.1. 如何调用本地写的DLL中的函数?7. 通用
6.2. 如何使用dumpbin.exe帮助描述 P/Invokes?
6.3. 如何为微软.net精简框架写非托管代码?
6.4. 如何调用 P/Invoke GetTickCount?
6.5. 如何获得系统还有多少可用内存?
6.6. 如何是窗口一直保持最小化?
6.7. 在微软.net精简框架上调用系统函数时,如何装配数据类型?
6.8. 如何得到一个窗体或控件的句柄 (HWND) ?
6.9. 如何使用性能计数器功能?
6.10. 调用本地代码时,数据类型有什么限制?What are the limitations on marshalling types via P/Invoke?
6.11. 调用GetLastError时,总是获得不定的代码?
6.12. 调用本地代码时,有没有参数数量的限制?
6.13. 调用本地代码时,为什么得到"NotSupportedException"异常?
6.14. 如何把 byte[] 转换成 IntPtr?
6.15. Why do I get a MissingMethodException when I call a function from a native DLL?
6.16. How do I set the system time?
6.17. How do I programmatically soft reset the device?
6.18. How can I put an icon on the title bar regardless of the which form is active?
6.19. How do I disable and capture hardware buttons?
6.20. How do I hide the start icon?
6.21. How do I enumerate, create, and terminate processes?
6.22. Where can I find a centralized library of P/Invoke samples?
6.23. How do I play and record .WAV audio files with the Waveform Audio Inteface?
7.1. 如何确定应用程序的主目录?8. 通讯和Web服务
7.2. 如何计算精确的时间间隔?
7.3. 如何把嵌入式资源当作一个流(Stream)?
7.4. 为什么得到一个"An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll"的错误?
7.5. 如何使用性能监视器?
7.6. 如何取消一个程序的关闭?
7.7. 如何在我的程序中调用另一个应用程序?
7.8. .net精简框架的应用程序会建立什么线程?
7.9. 如何把byte数组转换成结构体?
7.10. 我可以建立一个委托(delegate)交给Invoke吗?
7.11. 如何在微软.net精简框架上使用电话API?
7.12. 如何在Pocket Pc上生成GUID?
7.13. 如何让我的.net精简框架程序和Pocket Outlook的数据结合?
7.14. 我可以判断.net精简框架中一个文件的版本吗?
7.15. 微软.net精简框架的后台处理有什么相关技术?
7.16. 在微软.net精简框架上使用多线程有什么技巧?
7.17. 如何在 智能设备应用 中使用混淆器?
7.18. 如何使用密码服务对数据进行加密或解密?
7.19. 如何在微软.net精简框架上获得Windows CE设备的唯一号码?
7.20. 如何在微软.net精简框架的应用程序上发送短消息?
7.21. 不使用Control.Name,可以判断事件的发送者吗?
7.22. 如何在线程中调用方法的参数?
7.23. 如何建立提醒程序和定时程序?
7.24. 如何播放声音?
7.25. 如何使用命令行参数?
7.26. 当使用已经释放的对象的方法或属性的时候,为什么得到一个异常?
7.27. 如何获得"Enter", "TAB", 和 "Arrow"按键的事件?
7.28. 如何删除一个只读文件?
7.29. How do I determine if a member exists at runtime?
7.30. How do I determine the device name programatically?
7.31. How do I build a C# Smart Device project from the command line?
7.32. How do I abort an executing thread?
7.33. Why can't I play a movie on the Pocket PC emulator?
7.34. How do I suppress Form titles from showing in the active applications list?
7.35. How do I access a Control from its instance name?
7.36. How do I detect the hardware directional pad buttons?
7.37. How do I get a double click event when only the Click event is supported?
7.38. How do I get onenter/onleave style notifications?
7.39. How do I use threading in a modal dialog that doesn't hang my app?
7.40. How do I round floating point numbers efficiently?
7.41. Why does Control.Invoke take so long when a modal dialog is displayed?
7.42. Is there a way to retrieve the culture information of an Assembly?
8.1. 如何通过TCP Socket向桌面机发送数据?9. SQL CE 和 数据
8.2. 为什么不能访问本机上的Web服务?
8.3. 如何在微软.net精简框架上调用Web服务
8.4. 如何通过代理服务器提交HTTP GET申请?
8.5. 如何使用Web服务?
8.6. 如何使用MapPoint3.0得到地图?
8.7. 如何使用MapPoint3.0获得地图和方向?
8.8. Is NTLM authentication supported by the .NET Compact Framework?
8.9. When using blocking Sockets, why does Send throw an InvalidOperationException when blocking is set to false?
8.10. How do I create an http-server?
8.11. Why do I get an exception when calling SetSocketOption with ReuseAddress set?
8.12. Why do I get a socket error using SSL to communicate with a server via the WebRequest namespace?
9.1. 使用.net精简框架、SQL Server CE 和 复制 开发应用程序时,要注意些什么?10. 其他信息
9.2. 如何在微软.net精简框架上使用合并复制(Merge Replication)?
9.3. 如何将ADO.NET数据和XML绑定?
9.4. 如何建立SQL Server CE的数据库?
9.5. 如何向SQL Server CE提交一个带参数的查询?
9.6. Why does using RDA and the push method fail with error 27750?
10.1. Pocket TaskVision 程序11. 连通性
10.2. 建立基于微软.net精简框架的进程管理器
10.3. 使用微软.net精简框架开发移动游戏
10.4. 制作一个微软.net精简框架的DateTimePicker控件
10.5. 写一个捕捉Pocket PC签名的程序
10.6. 有没有非微软的网站提供在.net精简框架上开发应用的信息?
11.1. 为什么不同通过ActiveSync把程序部署到Windows CE的设备上?12. Smartphone
11.2. 为什么不能通过ActiveSync调试 CEPC 或其他 x86 的Windows CE设备?
11.3. 为什么当设备上的Toolhelp.dll文件丢失后,调试就会失败?
11.4. 为什么当网络协议数超过50个的时候,就不能向设备发布程序?
11.5. 为什么卸载ActiveSync后,不能通过ActiveSync向设备发布?
11.6. 为什么本地化的机器名或用户名或导致向设备发布程序的失败?
11.7. 为什么当前用户不属于Administrators组的时候,不能向设备发布程序?
11.8. 为什么向Pocket PC或模拟器发布的时候出现 sharing violation 的错误?
11.9. 为什么在.NET Server的计算机上第一次使用模拟器的时候,得到一个安全警告消息?
11.10. 为什么在模拟器刚开始运行的时候出现关于找不到文件的错误信息?
11.11. 为什么第一次用模拟器发布时,会出现偶尔的错误?
11.12. 为什么第一次用Connect按钮连接模拟器并发布程序的时候失败了?
11.13. 为什么当计算机没有网络连接的时候,用模拟器调试程序会出现错误?
11.14. 为什么当模拟器使用了一个COM端口的时候不启动不了(黑屏)?
11.15. 为什么Visual Studio .NET 2003的模拟器不能和eMbedded Visual Tools的模拟器同时使用?
11.16. 为什么没有ActiveSync连接的时候不能通过TCP连接向设备发布程序?
11.17. How can I allow Activesync to connect to an Emulator session from Visual Studio .NET 2003?
11.18. How can I copy files to the device currently connected to desktop ActiveSync?
11.19. Why does the Visual Studio debugger fail to connect to an ARMV4I device?
12.1. Where can I get the latest Smartphone SDK?
12.2. What are the rules for Smartphone menus?
12.3. Why are there disabled controls in the toolbox when creating a Smartphone project?
12.4. Does Smartphone support RAM installs of the .NET Compact Framework?
12.5. How do I set the title of a fullscreen multiline edit control window?
12.6. How can I generate Smartphone CABWizSP XML docs from existing Pocket PC CAB files?
12.7. How can I send characters and strings to the Smartphone 2003 Emulator via ActiveSync?
12.8. How do I programmatically set the Smartphone input mode?
1.1. 什么是微软 .net精简框架?
微软.net精简框架是.net框架为智能设备开发的平台,是实现微软的目标:“为用户提供精彩的体验--任何时间、任何地点、任何设备” 的关键部分。.net精简框架把托管代码的世界从web服务带到了智能设备上, 允许在个人数字助理(PDA)、移动电话、机顶盒设备上的 安全的、可下载的应用。
http://msdn.microsoft.com/mobility/prodtechinfo/devtools/netcf/overview/default.aspx
1.2. 我需要什么工具才能开发.net精简框架的应用?
Visual Studio .NET 2003 是在Pocket PC 2000、Pocket PC 2002和Windows CE.NET 4.1上开发.net精简框架所需要的, .net精简框架与Visual Studio .NET 2003一同发售.
http://msdn.microsoft.com/mobility/prodtechinfo/devtools/vstudio/default.aspx
其他Windows移动平台开发包可以在以下地方获得:
Windows Mobile 2003 Pocket PC SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=9996b314-0364-4623-9ede-0b5fbb133652&displaylang=en
Windows Mobile 2003 Smartphone SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=a6c4f799-ec5c-427c-807c-4c0f96765a81&displaylang=en
这篇文章将介绍如何使用.net精简框架和Visual Studio .NET 2003下开发健壮的智能设备应用程序.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfgetstarted.asp
1.3. 哪里可以下载最新的工具和相关软件?
Visual Studio .NET 2003试用版可以在这里获得:
http://msdn.microsoft.com/vstudio/productinfo/trial/default.aspx
最新的.net精简框架和补丁集可以在这里获得:
http://msdn.microsoft.com/mobility/downloads/default.aspx
1.4. .net精简框架支持些什么设备?
.net精简框架可以在Pocket PC 2000, Pocket PC 2002, Windows Mobile 2003的Pocket PC 和 基于Windows CE.NET 4.1嵌入式系统的Pocket PC、智能手机 上运行。
1.5. .net精简框架以后将支持什么设备?
.net精简框架将被集成到微软系统中并成为一部分,包括未来的Pocket PC设备,Pocket PC电话版,智能手机,车载Windows CE系统,MSTV。 各种设备的发布时间待定。
.net精简框架将作为Windows CE .NET 4.1系统组件的一部分,因此允许OEM厂商使用PlatformBuilder把.net精简框架集成到新的Windows CE设备中。
1.6. 调试程序时为什么会出现“与模拟器建立连接失败”的错误(刚开始执行程序的时候)?
下面这个连接将告诉你如何设置调试和排错。
http://download.microsoft.com/download/c/d/b/cdbff573-73fb-4f9f-a464-c5adc890e1ae/Readme.htm
1.7. .net框架和.net精简框架之间有什么区别?
.NET框架 和 .net精简框架 的关系:
http://msdn.microsoft.com/library/en-us/dv_evtuv/html/etconComparisonsWithNETFramework.asp
在线查看.net精简框架类库关系工具:
http://msdn.microsoft.com/library/en-us/dv_spchk/html/NET_Compact_Framework.htm
1.8. .net精简框架的补丁有什么改进?
.net精简框架 SP1 修正了许多漏洞,查看修正项目列表:
http://www.microsoft.com/downloads/details.aspx?familyid=1f62a2a3-7282-4ba9-b26b-2267e972501d&displaylang=en
1.9. Poclet PC上的.net精简框架开发和Windows CE .NET上的.net精简框架开发有什么不同?
这篇文章将描述在Pocket PC和Windows CE.NET平台上开发基于.net 精简框架的应用程序的区别之处。
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfPPCtoCE.asp
1.10. 哪里有更多的关于建立.net精简框架上的应用程序的信息?
以下资源能教会您怎样建立.net精简框架应用程序:
ToolBoxItemFilterAttribute("NETCF",ToolBoxItemFilterType.Require)
ToolBoxItemFilterAttribute("System.CF.Windows.Forms", ToolBoxITemFilterType.Custom)
2.1. 怎样建立一个图形对象?
有很多种方法可以建立图形对象,看你怎么用:
在OnPaint中,使用object参数提供的PaintEventArgs参数:
//C#在程序的其他部分,利用控件的一个方法,可以用来建立任意控件的图形对象:
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawLine(...);
}
'VB
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
e.Graphics.DrawLine(...)
End Sub 'OnPaint
//C#直接画到bitmap位图文件中:
using System.Drawing;
Graphics g = this.CreateGraphics();
'VB
Imports System.Drawing
Dim g As Graphics = Me.CreateGraphics()
//C#2.2. 怎样优化GDI+?
using System.Drawing;
Bitmap bm = new Bitmap(10,10);
Graphics g = Graphics.FromImage(bm);
'VB
Imports System.Drawing
Dim bm As New Bitmap(10, 10)
Dim g As Graphics = Graphics.FromImage(bm)
//C#以下代码描述了如何根据图象左上角的颜色设置透明色。
using System.Drawing.Imaging;
ImageAttributes attr = new ImageAttributes();
'VB
Imports System.Drawing.Imaging
Dim attr As New ImageAttributes()
//C#以下方法可以准确的设置颜色:
attr.SetColorKey(bmp.GetPixel(0,0), bmp.GetPixel(0,0));
'VB
attr.SetColorKey(bmp.GetPixel(0,0), bmp.GetPixel(0,0))
//C#图象会被重载的Graphics.DrawImage方法重画,并且使用ImageAttributes对象作为一个参数parameter:
attr.SetColorKey(Color.FromArgb(255,0,255),Color.FromArgb(255,0,255));
attr.SetColorKey(Color.Fuchsia, Color.Fuchsia);
'VB
attr.SetColorKey(Color.FromArgb(255,0,255),Color.FromArgb(255,0,255))
attr.SetColorKey(Color.Fuchsia, Color.Fuchsia)
//C#2.5. 为什么从TextBox上调用CreateGraphics会失败?
g.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height,GraphicsUnit.Pixel, attr);
'VB
g.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height,GraphicsUnit.Pixel, attr)
//C#2.7. Can I set the width of a pen?
using System.Drawing;
protected override void OnPaint(PaintEventArgs e)
{
string s = "Hello World"
Pen pen = new Pen(Color.Fuchsia);
Font font = new Font("Arial", 18, FontStyle.Regular);
Brush brush = new SolidBrush(Color.Black);
SizeF sSize = e.Graphics.MeasureString(s, font);
Rectangle r = new Rectangle(9, 199,(int)sSize.Width + 1, (int)sSize.Height + 1);
e.Graphics.DrawRectangle(pen, r);
e.Graphics.DrawString(s, font, brush, 10.0f, 200.0f);
base.OnPaint (e);
}
'VB
Imports System.Drawing
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim s As String = "Hello World"
Dim pen As New Pen(Color.Fuchsia)
Dim font As New Font("Arial", 18, FontStyle.Regular)
Dim brush = New SolidBrush(Color.Black)
Dim sSize As SizeF = e.Graphics.MeasureString(s, font)
Dim r As New Rectangle(9, 199, Fix(sSize.Width) + 1, Fix(sSize.Height) + 1)
e.Graphics.DrawRectangle(pen, r)
e.Graphics.DrawString(s, font, brush, 10F, 200F)
MyBase.OnPaint(e)
End Sub 'OnPaint
//C#2.9. Why can't I load an image?
using System.Drawing;
using System.Reflection;
Bitmap m_bmpOriginal;
Bitmap m_bmpZoom;
private void Form1_Load(object sender, System.EventArgs e)
{
Assembly asm = Assembly.GetExecutingAssembly();
m_bmpOriginal = new Bitmap(asm.GetManifestResourceStream(asm.GetName().Name
+ ".MyImage.bmp"));
// Take the center quarter of m_bmpOriginal
// and create stetch it into m_bmpZoom of the same size
m_bmpZoom = new Bitmap(m_bmpOriginal.Width, m_bmpOriginal.Height);
Graphics gZoom = Graphics.FromImage(m_bmpZoom);
Rectangle srcRect = new Rectangle(m_bmpOriginal.Width / 4, m_bmpOriginal.Height / 4,
m_bmpOriginal.Width / 2, m_bmpOriginal.Height / 2);
Rectangle dstRect = new Rectangle(0, 0, m_bmpZoom.Width, m_bmpZoom.Height);
gZoom.DrawImage(m_bmpOriginal, dstRect, srcRect, GraphicsUnit.Pixel);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(m_bmpOriginal, 0, 0);
e.Graphics.DrawImage(m_bmpZoom, 125, 0);
base.OnPaint (e);
}
'VB
Imports System.Drawing
Imports System.Reflection
Private m_bmpOriginal As Bitmap
Private m_bmpZoom As Bitmap
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim asm As [Assembly] = [Assembly].GetExecutingAssembly()
m_bmpOriginal = New Bitmap(asm.GetManifestResourceStream((asm.GetName().Name _
+ ".MyImage.bmp")))
' Take the center quarter of m_bmpOriginal
' and create stetch it into m_bmpZoom of the same size
m_bmpZoom = New Bitmap(m_bmpOriginal.Width, m_bmpOriginal.Height)
Dim gZoom As Graphics = Graphics.FromImage(m_bmpZoom)
Dim srcRect As New Rectangle(m_bmpOriginal.Width / 4, m_bmpOriginal.Height / 4, _
m_bmpOriginal.Width / 2, m_bmpOriginal.Height / 2)
Dim dstRect As New Rectangle(0, 0, m_bmpZoom.Width, m_bmpZoom.Height)
gZoom.DrawImage(m_bmpOriginal, dstRect, srcRect, GraphicsUnit.Pixel)
End Sub 'Form1_Load
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
e.Graphics.DrawImage(m_bmpOriginal, 0, 0)
e.Graphics.DrawImage(m_bmpZoom, 125, 0)
MyBase.OnPaint(e)
End Sub 'OnPaint
3.1. 怎样建立一个PocketPC的设置程序?
这篇文章告诉您如何建立一个单独的.msi文件,可以运行并把应用安装到不同的Pocket PC设备上。整个过程都是自动的,所以很容易把所有需要的组件都打包到.msi文件中。包含C#和Microsoft Visual Basic .NET代码。
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfdeployment.asp
3.2. 哪个发布包可以包括在我的安装程序中?
您可以为您的用户提供一个最终的发布包,以帮助他们升级设备。您不能拆开这个发布包把内容给您的用户。但是,您可以拆开开发人员的发布包把内容给您的用户。
3.3. 怎样可以建立一个不需要.net框架的安装程序?
这篇文章讨论了如何成功的安装一个Pocket PC的应用:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnppc2k/html/ppc_allation.asp
3.4. 怎样建立不受PocketPC系统约束的CAB安装文件?
您可以建立一个.inf文件生成一个适合任何Pocket PC设备的应用程序安装文件。查看示例代码:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/cabfile.aspx
3.5. 为什么不同的处理器会有不同的CAB安装文件?
每一个CAB文件都包含一小段检测智能设备上的.net精简框架版本的代码。这个功能是处理器/平台特有的,不同的CAB文件根据处理器类型绑定不同的代码。
3.6. How do I create a desktop installer that detects the presence of the .NET Compact Framework on the target device and installs it if necessary?
The article titled "Creating an MSI Package that Detects and Updates the .NET Compact Framework" in the MSDN Library describes a technique that may be used:
http://msdn.microsoft.com/mobility/understanding/articles/default.aspx?pull=/library/en-us/dnnetcomp/html/netcfdepl.asp
3.7. How do I deploy a .NET Compact Framework Service Pack to the emulator?
Download and install to your desktop development PC a "Developer" version of the service pack (the download title will read something like: "Microsoft® .NET Compact Framework 1.0 SPx Developer Redistributable") from:
http://msdn.microsoft.com/mobility/downloads/updates/default.aspx
The next step is to copy the appropriate .NET Compact Framework cab file (as per next paragraph) to the emulator. From within the emulator point File Explorer to a share on your PC and then copy and paste the cab to somewhere on the emulator's file system. Now launch the cab file from File Explorer and answer "Yes" if asked to overwrite anything.
Emulator | CAB File |
Pocket PC 2002 | netcf.core.ppc3.x86.cab |
Windows Mobile 2003 for Pocket PC | netcf.core.wce4.x86.cab |
Windows Mobile 2003 for Smartphone | RAM installs not supported |
4.1. 怎样建立一个全屏的窗体?
您必须把WindowState属性设置为最大化。做一个看不见的窗体,如把全屏的图片放到窗体中,您需要把FormBorderStyle设置为None,关掉ControlBox删掉窗体中所有的菜单。
//C#4.2. 什么时候用窗体的构造器?什么时候用窗体的Load事件?
this.WindowState = FormWindowState.Maximized;
this.FormBorderStyle = FormBorderStyle.None;
this.ControlBox = false;
this.Menu = null;
'VB
Me.WindowState = FormWindowState.Maximized
Me.FormBorderStyle = FormBorderStyle.None
Me.ControlBox = False
Me.Menu = Nothing
//C#4.4. 怎样在.net精简框架上建立多窗体系统结构?
this.MinimizeBox = false;
'VB
Me.MinimizeBox = False
4.12. Why does showing a MessageBox on Windows Mobile 2003 for Smartphone with the Abort, Retry, and Fail set of buttons or the Yes, No, Cancel set of buttons, or the third button as the default button result in a NotSupportedException?
Windows Mobile 2003 for Smartphone only supports 1 or 2 button MessageBoxes.
4.13 How do I get an icon in the Pocket PC Start Menu Most Recently Used (MRU) List?
Create a shortcut to your application somewhere under /windows/start menu/programs. When your application is launched from this shortcut an icon for your applications will appear the MRU list.
//c#4.15 Why can't I show a Form that has been closed?
Rectangle screen = Screen.PrimaryScreen.Bounds;
this.Location = new Point((screen.Width - this.Width) / 2,
(screen.Height - this.Height ) / 2);
'VB
Dim theScreen As Rectangle
theScreen = Screen.PrimaryScreen.Bounds()
Me.Location = New Point((theScreen.Width - Me.Width) / 2, _
(theScreen.Height - Me.Height) / 2)
// C#
using System.Runtime.InteropServices;
using System.Reflection;
private void Form1_Load(object sender, System.EventArgs e)
{
this.Text = string.Format("Form {0}", new Random().Next());
}
[DllImport("CoreDll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("CoreDll")]
public static extern int SetWindowText(IntPtr hWnd, string lpString);
protected override void OnResize(EventArgs e)
{
Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
IntPtr hWnd = FindWindow("#NETCF_AGL_PARK_",
asm.GetModules()[0].FullyQualifiedName);
if (hWnd != IntPtr.Zero)
SetWindowText(hWnd, "#42");
base.OnResize (e);
}
'VB
Imports System.Runtime.InteropServices
Imports System.Reflection
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.Text = String.Format("Form {0}", New Random().Next())
End Sub 'Form1_Load
<DllImport("CoreDll")> _
Public Shared Function FindWindow(ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("CoreDll")> _
Public Shared Function SetWindowText(ByVal hWnd As IntPtr, _
ByVal lpString As String) As Integer
End Function
Protected Overrides Sub OnResize(ByVal e As EventArgs)
Dim asm As [Assembly] = System.Reflection.Assembly.GetExecutingAssembly()
Dim hWnd As IntPtr = FindWindow("#NETCF_AGL_PARK_", _
asm.GetModules()(0).FullyQualifiedName)
If hWnd.ToInt32() <> IntPtr.Zero.ToInt32() Then
SetWindowText(hWnd, "#42")
End If
MyBase.OnResize(e)
End Sub 'OnResize
5.1. 怎样建立一个带有图形或支持多行的按钮?
建立一个带有图形或支持多行的按钮需要使用自定义控件。自定义控件能继承button的paint方法,以及其他任何需要的自定义数据。参考以下连接获得更多关于自定义控件的信息:
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/customctrlscompactfx.asp
快速入门教程告诉你如何建立一个带图像的按钮:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/picturebutton.aspx
5.2. TextBox.AcceptsReturn在.net精简框架下是怎样工作的?
虽然设置了AcceptsReturn为false,但它还是按true的方式来操作。你可以写一个继承TextBox的类,在KeyPress事件中实现对Enter的处理。
5.3. 当数据载入ComboBox的时候,为什么SelectedIndexChanged事件没有被触发?
这是一个已经知道的问题,将在以后的.net精简框架中发布。
5.4. Show和ShowDialog有什么不同?
ShowDialog会把一个窗体以 模式 方式显示,这是一种独占调用方式,知道窗体关闭才会返回。这个方法将返回一个DialogResult枚举,表示关闭的条件。
Show是一种非独占的调用方式,和显示一个控件一样,可以立刻返回,没有返回参数。显示一个控件意味着Visible属性被设置为true,直到Hide方法被调用,Visible方法才会变为false。
5.5. 为什么我不能建立右键菜单分离器?(separator)
这是一个已经知道的BUG,把右键菜单设置为分割线,将抛出NotSupportedException错误。这个问题是由于WinCE系统有个限制,不允许在已经加入右键菜单的菜单项设置为分隔符,并且菜单的父类是一个控件。在Visual Studio 2003种,设计器分割移动应用代码的方式和PC上的应用程序类似。这是导致此问题的原因。解决的方法是,把右键菜单单独放在InitilizeComponent方法外的地方。
5.6. 运行时把ImageList赋给ToolBar时,为什么图象不出现?
你可以在窗体载入的时候把ImageList分配给ToolBar,但重新应用图像在ToolBar上的顺序。在设置ToolBar的ImageList之前 设置ToolBar按钮的图像顺序是不被支持的。
5.7. 怎样把光标设置成等待状态?
这段代码可以把光标设置成等待光标:
//C#这段代码可以把光标设置为默认:
Cursor.Current = Cursors.WaitCursor;
'VB
Cursor.Current = Cursors.WaitCursor
//C#5.8. 如何在菜单项中显示符号:&?
Cursor.Current = Cursors.Default;
'VB
Cursor.Current = Cursors.Default
//C#5.28. 为什么NumericUpDown控件能接受decimal类型的值,但不会显示大于2^16的值?
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
this.BackColor = Parent.BackColor;
}
'VB
Protected Overrides Sub OnParentChanged(ByVal e As EventArgs)
MyBase.OnParentChanged(e)
Me.BackColor = Parent.BackColor
End Sub 'OnParentChanged
//C#5.32. How do I add a subnode to every node in a TreeView?
using System.Runtime.InteropServices;
const uint SIPF_OFF = 0x0;
const uint SIPF_ON = 0x1;
[DllImport("coredll.dll")]
private extern static void SipShowIM(uint dwFlag);
'VB
Imports System.Runtime.InteropServices
Const SIPF_OFF As Integer = &H0
Const SIPF_ON As Integer = &H1
<DllImport("coredll.dll")> _
Private Shared Function SipShowIM(ByVal dwFlag As Integer) As Integer
End Function
//C#5.33. How do I determine the number of rows or columns in a DataGrid?
foreach (TreeNode node in treeView1.Nodes)
{
node.Nodes.Add(new TreeNode("SubNode"));
}
'VB
Dim node As TreeNode
For Each node In treeView1.Nodes
node.Nodes.Add(New TreeNode("SubNode"))
Next node
//C#If the DataGrid is bound to the DataView you can also use DataView.Count.
DataSet ds = new DataSet();
int numRows = ds.Tables[0].Rows.Count;
int numCols = ds.Tables[0].Columns.Count;
'VB
Dim ds As New DataSet()
Dim numRows As Integer = ds.Tables(0).Rows.Count
Dim numCols As Integer = ds.Tables(0).Columns.Count
//C#5.36. How do I get notified when the user clicks on a treeview node?
public Control GetNextControl(Control ctl, bool forward)
{
int curIndex = this.Controls.IndexOf(ctl);
if (forward)
{
if (curIndex < this.Controls.Count)
curIndex++;
else
curIndex = 0;
}
else
{
if (curIndex > 0)
curIndex--;
else
curIndex = this.Controls.Count - 1;
}
return this.Controls[curIndex];
}
'VB
Public Function GetNextControl(ByVal ctl As Control, _
ByVal forward As Boolean) As Control
Dim curIndex As Integer = Me.Controls.IndexOf(ctl)
If forward Then
If curIndex < Me.Controls.Count Then
curIndex += 1
Else
curIndex = 0
End If
Else
If curIndex > 0 Then
curIndex -= 1
Else
curIndex = Me.Controls.Count - 1
End If
End If
Return Me.Controls(curIndex)
End Function 'GetNextControl
//C#
using System.Drawing;
using System.IO;
using System.Reflection;
// Loaded as content example
private void Form1_Load(object sender, System.EventArgs e)
{
this.imageList1.Images.Add(new Icon(File.Open("fullFileName.ico",
FileMode.Open)));
this.toolBar1.Buttons[0].ImageIndex = 0;
}
// Loaded as a resource example
private void Form1_Load(object sender, System.EventArgs e)
{
this.imageList1.Images.Add(new
Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream(
".filename.ico")));
this.toolBar1.Buttons[0].ImageIndex = 0;
}
'VB
Imports System.Drawing
Imports System.IO
Imports System.Reflection
' Loaded as content example
Private Sub Form1_Load1(ByVal sender As Object, ByVal e As System.EventArgs)
Me.imageList1.Images.Add(New Icon(File.Open("fullFileName.ico", _
FileMode.Open)))
Me.toolBar1.Buttons(0).ImageIndex = 0
End Sub 'Form1_Load1
' Loaded as a resource example
Private Sub Form1_Load2(ByVal sender As Object, ByVal e As System.EventArgs)
Me.imageList1.Images.Add(New _
Icon([Assembly].GetExecutingAssembly().GetManifestResourceStream( _
".filename.ico")))
Me.toolBar1.Buttons(0).ImageIndex = 0
End Sub 'Form1_Load2
6.1. 如何调用本地代码写的DLL中的函数?
本地DLL代码可以通过系统的Invoke (P/Invoke)方法调用。这些文章提供了如何实现调用和更多的调用技巧:
//C#6.6. 如何是窗口一直保持最小化?
using System.Runtime.InteropServices;
public class MEMORYSTATUS
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}
[DllImport("CoreDll.dll")]
public static extern void GlobalMemoryStatus
(
MEMORYSTATUS lpBuffer
);
[DllImport("CoreDll.dll")]
public static extern int GetSystemMemoryDivision
(
ref uint lpdwStorePages,
ref uint lpdwRamPages,
ref uint lpdwPageSize
);
public void Test()
{
uint storePages = 0;
uint ramPages = 0;
uint pageSize = 0;
int res = GetSystemMemoryDivision(ref storePages, ref ramPages, ref pageSize);
MEMORYSTATUS memStatus = new MEMORYSTATUS();
GlobalMemoryStatus(memStatus);
}
'VB
Imports System.Runtime.InteropServices
Public Structure MEMORYSTATUS
Public dwLength As UInt32
Public dwMemoryLoad As UInt32
Public dwTotalPhys As UInt32
Public dwAvailPhys As UInt32
Public dwTotalPageFile As UInt32
Public dwAvailPageFile As UInt32
Public dwTotalVirtual As UInt32
Public dwAvailVirtual As UInt32
End Structure 'MEMORYSTATUS
<DllImport("coredll.dll")> _
Private Shared Sub GlobalMemoryStatus(ByRef ms As MEMORYSTATUS)
End Sub
<DllImport("CoreDll.dll")> _
Public Shared Function GetSystemMemoryDivision( _
ByRef lpdwStorePages As UInt32, _
ByRef lpdwRamPages As UInt32, _
ByRef lpdwPageSize As UInt32) As Integer
End Function
Public Shared Sub Test()
Dim storePages As UInt32
Dim ramPages As UInt32
Dim pageSize As UInt32
Dim res As Integer = GetSystemMemoryDivision(storePages, ramPages, pageSize)
Dim memStatus As New MEMORYSTATUS
GlobalMemoryStatus(memStatus)
End Sub 'Test
//C#6.7. 在微软.net精简框架上调用系统函数时,如何装配数据类型?
using System.Runtime.InteropServices;
[DllImport("CoreDll")]
public static extern IntPtr FindWindow(string className,string WindowsName);
[DllImport("CoreDll")]
public static extern bool ShowWindow(IntPtr hwnd,int nCmdShow);
const int SW_MINIMIZE = 6;
protected override void OnGotFocus(EventArgs e)
{
IntPtr hwnd = FindWindow(null, this.Text);
ShowWindow(hwnd, SW_MINIMIZE);
base.OnGotFocus(e);
}
'VB
Imports System.Runtime.InteropServices
<DllImport("CoreDll")> _
Public Shared Function FindWindow(ByVal className As String, ByVal WindowsName As String) As IntPtr
End Function
<DllImport("CoreDll")> _
Public Shared Function ShowWindow(ByVal hwnd As IntPtr,ByVal nCmdShow As Integer) As Boolean
End Function
Private Const SW_MINIMIZE As Integer = 6
Protected Overrides Sub OnGotFocus(ByVal e As EventArgs)
Dim hwnd As IntPtr = FindWindow(Nothing, Me.Text)
ShowWindow(hwnd, SW_MINIMIZE)
MyBase.OnGotFocus(e)
End Sub 'OnGotFocus
//C#6.9. 如何使用性能计数器功能?
[DllImport("coredll.dll"]
public static extern IntPtr GetCapture();
[DllImport("coredll.dll")]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
this.Text = "FindMe";
IntPtr hwnd1 = FindWindow(null, "FindMe");
this.Capture = true;
IntPtr hwnd2 = GetCapture();
this.Capture = false;
'VB
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function GetCapture() As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
Me.Text = "FindMe"
Dim deskWin As IntPtr = FindWindow(Nothing, "FindMe")
Me.Capture = True
Dim hwnd As IntPtr = GetCapture()
Me.Capture = False
//C#
[DllImport("CoreDll.dll")]
public static extern int QueryPerformanceFrequency(ref Int64 lpFrequency);
[DllImport("CoreDll.dll")]
public static extern int QueryPerformanceCounter(ref Int64 lpPerformanceCount);
private void TestTimer()
{
System.Int64 freq = 0;
if (QueryPerformanceFrequency(ref freq) != 0)
{
System.Int64 count1 = 0;
System.Int64 count2 = 0;
if (QueryPerformanceCounter(ref count1) != 0)
{
System.Threading.Thread.Sleep(1200);
QueryPerformanceCounter(ref count2);
System.Int64 time_ms = (count2 - count1) * 1000 / freq;
}
}
}
'VB
<DllImport("CoreDll.dll")> _
Public Shared Function QueryPerformanceFrequency(ByRef lpFrequency As Int64) As Integer
End Function
<DllImport("coredll.dll")> _
Public Shared Function QueryPerformanceCounter(ByRef lpPerformanceCount As Int64) As Integer
End Function
Private Sub TestTimer()
Dim freq As System.Int64 = 0
If QueryPerformanceFrequency(freq) <> 0 Then
Dim count1 As System.Int64 = 0
Dim count2 As System.Int64 = 0
If QueryPerformanceCounter(count1) <> 0 Then
System.Threading.Thread.Sleep(1200)
QueryPerformanceCounter(count2)
Dim time_ms As System.Int64 = (count2 - count1) * 1000 / freq
End If
End If
End Sub 'TestTimer
using System.Runtime.InteropServices;
[DllImport("coredll.dll", SetLastError=true)]
int myFoo(...);
Foo(...)
{
int rc = myFoo(...);
if (rc == false)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Foo failed");
}
}
//C#
[DllImport("coredll.dll", SetLastError=true)]
public static extern long RegOpenKey(
IntPtr hkey,
string lpSubKey,
ref IntPtr hkeyResult
);
public long OpenMySubKey()
{
IntPtr hkey = IntPtr.Zero;
return RegOpenKey(HKEY_CLASSES_ROOT, "MySubKey", ref hkey);
}
'VB
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function RegOpenKey(ByVal hkey As IntPtr, ByVal lpSubKey As String, ByRef hkeyResult As IntPtr) As Long
End Function
Public Function OpenMySubKey() As Long
Dim hkey As IntPtr = IntPtr.Zero
Return RegOpenKey(HKEY_CLASSES_ROOT, "MySubKey", hkey)
End Function 'OpenMySubKey
//C#也可以使用GCHandle指向对象。
unsafe
{
byte[] test = new byte[5];
fixed (byte* p = &test[0])
{
*p = 0xff;
}
}
//C#最后,可以使用LocalAlloc和Marshalling函数复制内存块得到数据块。
using System.Runtime.InteropServices;
byte[] test = new byte[5];
GCHandle hObject = GCHandle.Alloc(test, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
if(hObject.IsAllocated)
hObject.Free();
'VB
Imports System.Runtime.InteropServices
Dim test(4) As Byte
Dim hObject As GCHandle = GCHandle.Alloc(test, GCHandleType.Pinned)
Dim pObject As IntPtr = hObject.AddrOfPinnedObject()
If hObject.IsAllocated Then
hObject.Free()
End If
//C#
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalAlloc(uint uFlags, uint uBytes);
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalReAlloc(IntPtr hMem, uint uBytes, uint fuFlags);
public const uint LMEM_FIXED = 0;
public const uint LMEM_MOVEABLE = 2;
public const uint LMEM_ZEROINIT = 0x0040;
byte[] test = new byte[5];
IntPtr p = LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, (uint)test.Length);
if (p == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
Marshal.Copy(test, 0, p, test.Length);
}
'VB
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function LocalAlloc(ByVal uFlags As UInt32, ByVal uBytes As UInt32) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function LocalFree(ByVal hMem As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function LocalReAlloc(ByVal hMem As IntPtr, ByVal uBytes As UInt32, ByVal fuFlags As UInt32) As IntPtr
End Function
Public Const LMEM_FIXED As Integer = 0
Public Const LMEM_MOVEABLE As Integer = 2
Public Const LMEM_ZEROINIT As Integer = &H40
Dim test(4) As Byte
Dim p As IntPtr = LocalAlloc(Convert.ToUInt32(LMEM_FIXED Or LMEM_ZEROINIT), Convert.ToUInt32(test.Length))
If p.Equals(IntPtr.Zero) Then
Throw New OutOfMemoryException
Else
Marshal.Copy(test, 0, p, test.Length)
End If
//C#6.17. How do I programmatically soft reset the device?
using System.Runtime.InteropServices;
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
[DllImport("coredll.dll")]
public extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);
[DllImport("coredll.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
// Set the clock ahead one hour
SYSTEMTIME st = new SYSTEMTIME();
GetSystemTime(ref st);
st.wHour = (ushort)(st.wHour + 1 % 24);
SetSystemTime(ref st);
'VB
Imports System.Runtime.InteropServices
Public Structure SYSTEMTIME
Public wYear As UInt16
Public wMonth As UInt16
Public wDayOfWeek As UInt16
Public wDay As UInt16
Public wHour As UInt16
Public wMinute As UInt16
Public wSecond As UInt16
Public wMilliseconds As UInt16
End Structure
<DllImport("coredll.dll")> _
Public Shared Sub GetSystemTime(ByRef lpSystemTime As SYSTEMTIME)
End Sub
<DllImport("coredll.dll")> _
Public Shared Function SetSystemTime(ByRef lpSystemTime As SYSTEMTIME) As UInt32
End Function
'Set the clock ahead one hour
Dim st As New SYSTEMTIME
GetSystemTime(st)
st.wHour = Convert.ToUInt16(((Convert.ToInt32(st.wHour) + 1)) Mod 24)
SetSystemTime(st)
//C#6.18. How can I put an icon on the title bar regardless of the which form is active?
using System.Runtime.InteropServices;
public const uint FILE_DEVICE_HAL = 0x00000101;
public const uint METHOD_BUFFERED = 0;
public const uint FILE_ANY_ACCESS = 0;
public uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access)
{
return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method);
}
[DllImport("Coredll.dll")]
public extern static uint KernelIoControl
(
uint dwIoControlCode,
IntPtr lpInBuf,
uint nInBufSize,
IntPtr lpOutBuf,
uint nOutBufSize,
ref uint lpBytesReturned
);
uint ResetPocketPC()
{
uint bytesReturned = 0;
uint IOCTL_HAL_REBOOT = CTL_CODE(FILE_DEVICE_HAL, 15,
METHOD_BUFFERED, FILE_ANY_ACCESS);
return KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0,
IntPtr.Zero, 0, ref bytesReturned);
}
private void Form1_Load(object sender, System.EventArgs e)
{
DialogResult r = MessageBox.Show
(
"Are you sure you want to reset?",
"Test",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (r == DialogResult.Yes)
{
ResetPocketPC();
}
}
'VB
Public Const FILE_DEVICE_HAL As Integer = &H101
Public Const METHOD_BUFFERED As Integer = 0
Public Const FILE_ANY_ACCESS As Integer = 0
Public Function CTL_CODE( _
ByVal DeviceType As Integer, _
ByVal Func As Integer, _
ByVal Method As Integer, _
ByVal Access As Integer) As Integer
Return (DeviceType << 16) Or (Access << 14) Or (Func << 2) Or Method
End Function 'CTL_CODE
<DllImport("Coredll.dll")> _
Public Shared Function KernelIoControl _
( _
ByVal dwIoControlCode As Integer, _
ByVal lpInBuf As IntPtr, _
ByVal nInBufSize As Integer, _
ByVal lpOutBuf As IntPtr, _
ByVal nOutBufSize As Integer, _
ByRef lpBytesReturned As Integer _
) As Integer
End Function
Function ResetPocketPC() As Integer
Dim bytesReturned As Integer = 0
Dim IOCTL_HAL_REBOOT As Integer = CTL_CODE(FILE_DEVICE_HAL, _
15, METHOD_BUFFERED, FILE_ANY_ACCESS)
Return KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0, _
IntPtr.Zero, 0, bytesReturned)
End Function 'ResetPocketPC
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim r As DialogResult = MessageBox.Show( _
"Are you sure you want to reset?", _
"Test", _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Question, _
MessageBoxDefaultButton.Button2)
If r = DialogResult.Yes Then
ResetPocketPC()
End If
End Sub 'Form1_Load
//C#6.21. How do I enumerate, create, and terminate processes?
const uint SHFS_SHOWTASKBAR = 0x0001;
const uint SHFS_HIDETASKBAR = 0x0002;
const uint SHFS_SHOWSIPBUTTON = 0x0004;
const uint SHFS_HIDESIPBUTTON = 0x0008;
const uint SHFS_SHOWSTARTICON = 0x0010;
const uint SHFS_HIDESTARTICON = 0x0020;
[DllImport("aygshell.dll")]
static extern uint SHFullScreen(IntPtr hwndRequester, uint dwState);
[DllImport("coredll.dll")]
public static extern IntPtr GetCapture();
private void Form1_Load(object sender, System.EventArgs e)
{
Capture = true;
IntPtr hwnd = GetCapture();
Capture = false;
SHFullScreen(hwnd, SHFS_HIDESTARTICON);
}
'VB
Const SHFS_SHOWTASKBAR As Integer = &H1
Const SHFS_HIDETASKBAR As Integer = &H2
Const SHFS_SHOWSIPBUTTON As Integer = &H4
Const SHFS_HIDESIPBUTTON As Integer = &H8
Const SHFS_SHOWSTARTICON As Integer = &H10
Const SHFS_HIDESTARTICON As Integer = &H20
<DllImport("aygshell.dll")> _
Shared Function SHFullScreen(ByVal hwndRequester As IntPtr, ByVal dwState As Integer) As Integer
End Function
<DllImport("coredll.dll")> _
Public Shared Function GetCapture() As IntPtr
End Function
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Capture = True
Dim hwnd As IntPtr = GetCapture()
Capture = False
SHFullScreen(hwnd, SHFS_HIDESTARTICON)
End Sub 'Form1_Load
7.1. 如何确定应用程序的主目录?
使用Reflection,应用程序可以确定自己是从哪个目录启动的,也可以使用IO.Path命名空间来修改它。
//C#学习如何获得程序执行的当前目录。在Embedded Visual Basic中,程序执行的当前目录可以通过App.Path属性获得。执行程序的目录可以通过程序集的AssemblyName对象的获得,AssemblyName对象包含了程序集的所有描述:
using System.Reflection;
using System.IO;
// This is the full directory and exe name
String fullAppName = Assembly.GetExecutingAssembly().GetName().CodeBase;
// This strips off the exe name
String fullAppPath = Path.GetDirectoryName(fullAppName);
// This adds a file name to the path
String splashImageName = Path.Combine(fullAppPath, "myfile.txt");
'VB
Imports System.IO
Imports System.Reflection
' This is the full directory and exe name
Dim fullAppName As String = [Assembly].GetExecutingAssembly().GetName().CodeBase
' This strips off the exe name
Dim fullAppPath As String = Path.GetDirectoryName(fullAppName)
' This adds a file name to the path
Dim splashImageName As String = Path.Combine(fullAppPath, "myfile.txt")
//C#上面代码中, 字符串AssemblyName部分可以在运行时通过调用asm.GetName().Name得到。
using System.Reflection;
Assembly asm = Assembly.GetExecutingAssembly();
Bitmap bmpSprite = new Bitmap(asm.GetManifestResourceStream("AssemblyName.FileName"));
'VB
Imports System.Reflection
Dim asm As [Assembly] = [Assembly].GetExecutingAssembly()
Dim bmpSprite As New Bitmap(asm.GetManifestResourceStream("AssemblyName.FileName"))
//C#7.7. 如何在我的程序中调用另一个应用程序?
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
}
'VB
Protected Overrides Sub OnClosing(ByVal e As CancelEventArgs)
e.Cancel = True
End Sub 'OnClosing
//C#7.10. 我可以建立一个委托(delegate)交给Invoke吗?
public class MyClass
{
protected byte[] m_data = null;
// uint uiDummy
// short sDummy
// This is a bit unsafe so you should throw an
// exception or assert if the byte array length is
// not 6. A safer but less memory efficient approach
// would be to set m_data = new byte[6] and then copy
//bytes to m_data.
public MyClass(byte[] bytes) {m_data = bytes;}
// Get/Set the uint
public uint uiDummy
{
get {return BitConverter.ToUInt32(m_data, 0);}
set
{
Buffer.BlockCopy(BitConverter.GetBytes(value),0,m_data,0,BitConverter.GetBytes(value).Length);
}
}
// Get/Set the short
public short sDummy
{
get {return BitConverter.ToInt16(m_data, 4);}
set
{
Buffer.BlockCopy(BitConverter.GetBytes(value),0,m_data,4,BitConverter.GetBytes(value).Length);
}
}
}
byte[] fromFile = {1,1,1,1,2,2};
MyClass myClass = new MyClass(fromFile);
uint test1 = myClass.uiDummy; // 0x1010101
short test2 = myClass.sDummy; // 0x202
myClass.sDummy = 0x0505; // Test setting the short
uint test4 = myClass.uiDummy; // 0x1010101
short test5 = myClass.sDummy; // 0x505
'VB
Public Class ByteClass
Protected m_data As Byte() = Nothing
' uint uiDummy
' short sDummy
' This is a bit unsafe so you should throw an exception
' or assert if the byte array length is not 6. A safer
' but less memory efficient approach would be to set
' m_data = new byte[6] and then copy bytes to m_data.
Public Sub New(ByVal bytes() As Byte)
m_data = bytes
End Sub 'New
' Get/Set the uint
Public Property uiDummy() As UInt32
Get
Return BitConverter.ToUInt32(m_data, 0)
End Get
Set(ByVal Value As System.UInt32)
Buffer.BlockCopy(BitConverter.GetBytes(Value),0,m_data,0,BitConverter.GetBytes(Value).Length)
End Set
End Property
' Get/Set the short
Public Property sDummy() As Short
Get
Return BitConverter.ToInt16(m_data, 4)
End Get
Set(ByVal Value As Short)
Buffer.BlockCopy(BitConverter.GetBytes(Value),0,m_data,4,BitConverter.GetBytes(Value).Length)
End Set
End Property
End Class 'ByteClass
Dim fromFile As Byte() = {1, 1, 1, 1, 2, 2}
Dim testClass As New ByteClass(fromFile)
Dim test1 As System.UInt32 = testClass.uiDummy ' 0x1010101
Dim test2 As Short = testClass.sDummy ' 0x202
testClass.sDummy = &H505 ' Test short
Dim test4 As System.UInt32 = testClass.uiDummy ' 0x1010101
Dim test5 As Short = testClass.sDummy ' 0x505
//C#Although the following will compile, it will not work properly:
public void HandleMe(object o, EventArgs e) {...}
form.Invoke(new EventHandler(form.HandleMe));
'VB
Public Sub HandleMe(o As Object, e As EventArgs)
End Sub 'HandleMe
form.Invoke(New EventHandler(AddressOf form.HandleMe))
//C#7.11. 如何在微软.net精简框架上使用电话API?
public delegate void MyHandler();
public void HandleMeBadly() {...}
form.Invoke(new MyHandler(form.HandleMeBadly));
'VB
Delegate Sub MyHandler()
Public Sub HandleMeBadly()
End Sub 'HandleMeBadly
form.Invoke(New MyHandler(form.HandleMeBadly))
//C#7.15. 微软.net精简框架的后台处理有什么相关技术?
using System.Reflection;
String ver = Assembly.GetExecutingAssembly().GetName().Version.ToString();
'VB
Imports System.Reflection;
Dim ver As String = [Assembly].GetExecutingAssembly().GetName().Version.ToString()
//C#在Visual Studio 2003中测试的时候,可以通过继承开发环境设置命令行的参数。主菜单,选择 Project->Project Name Properties. 在Property Pages对话框中,选择 Configuration Properties->Debugging。在 Command Line Arguments 中输入字符串:text box.
static void Main(string[] args)
{
// Do your thing here
}
'VB
Shared Sub Main(ByVal args() As String)
'Do your thing here
End Sub
//C#
System.IO.FileInfo fi = new System.IO.FileInfo("filename");
// remove readonly attribute
fi.Attributes -= System.IO.FileAttributes.ReadOnly;
System.IO.File.Delete("filename");
'VB
Dim fi As New System.IO.FileInfo("filename")
'remove readonly attribute
fi.Attributes -= IO.FileAttributes.ReadOnly
System.IO.File.Delete("filename")
//C#
using System.Reflection;
using System.Drawing;
Bitmap bm = new Bitmap(200, 100);
int width = 0;
// Explicitly set one pixel for testing
int x = 199;
int y = 20;
Color pixColor = Color.Black;
bm.SetPixel(x,y,Color.Magenta);
// Get the "Width" property
PropertyInfo[] propInfo =
bm.GetType().GetProperties(BindingFlags.GetProperty |
BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < propInfo.Length; i++)
{
if (propInfo[i].Name == "Width")
{
width = (int)propInfo[i].GetValue(bm, null);
break;
}
}
// Call the GetPixel method
MethodInfo[] methInfo = bm.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < methInfo.Length; i++)
{
if (methInfo[i].Name == "GetPixel")
{
ParameterInfo[] paramInfo = methInfo[i].GetParameters();
if (paramInfo.Length == 2)
{
object[] xy = new object[2];
if (paramInfo[0].Name == "x")
{
xy[0] = x;
xy[1] = y;
}
else
{
xy[1] = x;
xy[0] = y;
}
pixColor = (Color)methInfo[i].Invoke(bm, xy);
break;
}
'VB
Imports System.Reflection
Imports System.Drawing
Dim bm As New Bitmap(200, 100)
Dim width As Integer = 0
' Explicitly set one pixel for testing
Dim x As Integer = 199
Dim y As Integer = 20
Dim pixColor As Color = Color.Black
bm.SetPixel(x, y, Color.Magenta)
' Get the "Width" property
Dim propInfo As PropertyInfo() = _
bm.GetType().GetProperties((BindingFlags.GetProperty Or _
BindingFlags.Public Or BindingFlags.Instance))
Dim i As Integer
For i = 0 To propInfo.Length - 1
If propInfo(i).Name = "Width" Then
width = Fix(propInfo(i).GetValue(bm, Nothing))
Exit For
End If
Next i
' Call the SetPixel method
Dim methInfo As MethodInfo() = bm.GetType().GetMethods((BindingFlags.Public _
Or BindingFlags.Instance))
For i = 0 To methInfo.Length - 1
If methInfo(i).Name = "GetPixel" Then
Dim paramInfo As ParameterInfo() = methInfo(i).GetParameters()
If paramInfo.Length = 2 Then
Dim xy(1) As Object
If paramInfo(0).Name = "x" Then
xy(0) = x
xy(1) = y
Else
xy(1) = x
xy(0) = y
End If
pixColor = CType(methInfo(i).Invoke(bm, xy), Color)
Exit For
End If
End If
Next i
//C#
String devName = System.Net.Dns.GetHostName();
'VB
Dim devName As String = System.Net.Dns.GetHostName()
set CFPath=%SystemDrive%/Program Files/Microsoft Visual Studio .NET 2003/
CompactFrameworkSDK/v1.0.5000/Windows CE
csc Form1.cs /noconfig /nostdlib /lib:"%CFPath%" /r:"%CFPath%/system.dll";"%CFPath%/
system.drawing.dll";"%CFPath%/system.windows.forms.dll";"%CFPath%/mscorlib.dll"
//C#
string AppName = "MyApp";
Form1 form1 = new Form1();
this.Text = "";
form1.Text = AppName;
form1.ShowDialog();
this.Text = AppName;
'VB
Dim AppName As String = "MyApp"
Dim form1 As New Form1()
Me.Text = ""
form1.Text = AppName
form1.ShowDialog()
Me.Text = AppName
//C#
private void Form1_Load(object sender, System.EventArgs e)
{
ComboBox c = (ComboBox)this.ControlFromName("combobox1");
c.Items.Add("1");
this.GetControls();
}
private Control ControlFromName(string name)
{
object o = this.GetType().GetField(name,
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.IgnoreCase).GetValue(this);
return((Control)o);
}
private void GetControls()
{
System.Reflection.FieldInfo[] fis = this.GetType().GetFields
(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.IgnoreCase
);
foreach(System.Reflection.FieldInfo fi in fis)
{
if (fi.GetValue(this) is Control)
MessageBox.Show(fi.Name);
}
}
'VB
Private Function ControlFromName(ByVal name As String) As Control
Dim o As ObjectDim o As Object
o = Me.GetType().GetField(name, Reflection.BindingFlags.NonPublic Or _
Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.IgnoreCase).GetValue(Me)
Return (CType(o, Control))
End Function
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim c As ComboBox
c = CType(ControlFromName("_combobox1"), ComboBox)
c.Items.Add("1")
Me.GetControls()e.GetControls()
End Sub
Private Sub GetControls()
Dim fis As System.Reflection.FieldInfo()
fis = Me.GetType().GetFields(Reflection.BindingFlags.NonPublic Or _
Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.IgnoreCase)
For Each fi As Reflection.FieldInfo In fis
If TypeOf (fi.GetValue(Me)) Is Control Then
MessageBox.Show(fi.Name)
End Ifnd If
Next
End Sub
//C#7.37. How do I get a double click event when only the Click event is supported?
protected override void OnKeyDown(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
MessageBox.Show("Up Key Pressed");
break;
case Keys.Down:
MessageBox.Show("Down Key Pressed");
break;
case Keys.Left:
MessageBox.Show("Left Key Pressed");
break;
case Keys.Right:
MessageBox.Show("Right Key Pressed");
break;
}
base.OnKeyDown (e);
}
'VB
Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
Select Case e.KeyCode
Case Keys.Up
MessageBox.Show("Up Key Pressed")
Case Keys.Down
MessageBox.Show("Down Key Pressed")
Case Keys.Left
MessageBox.Show("Left Key Pressed")
Case Keys.Right
MessageBox.Show("Right Key Pressed")
End Select
MyBase.OnKeyDown(e)
End Sub 'OnKeyDown
//C#7.40. How do I round floating point numbers efficiently?
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
public interface IModelessDialogCallback
{
void DialogResultCallback(DialogResult result);
}
public class Test : System.Windows.Forms.Form, IModelessDialogCallback
{
ModelessDialog dlg;
Button bShow;
int counter = 0;
protected override void OnLoad(EventArgs e)
{
this.Text = "Modal(less) Dialog Example";
this.bShow = new Button();
this.bShow.Parent = this;
this.bShow.Bounds = new Rectangle (10, 10, 150, 30);
this.bShow.Text = "Show Dialog";
this.bShow.Click += new EventHandler(this._Click);
this.dlg = new ModelessDialog(this);
}
private void _Click(object o, EventArgs e)
{
this.Enabled = false;
this.bShow.Text = "waiting for dlg";
dlg.Show();
}
public void DialogResultCallback(DialogResult result)
{
MessageBox.Show("dialog returned: " + (result == DialogResult.OK ? "OK" : "Cancel"));
this.Enabled = true;
this.bShow.Text = "Show Dialog:" + ++counter;
}
public static void Main()
{
Application.Run(new Test());
}
}
public class ModelessDialog : Form
{
IModelessDialogCallback parent;
Button bOK, bCancel;
public ModelessDialog(IModelessDialogCallback parent)
{
this.parent = parent;
this.Text = "Modeless Dialog";
this.bOK = new Button();
this.bOK.Parent = this;
this.bOK.Bounds = new Rectangle (10, 10, 150, 30);
this.bOK.Text = "OK";
this.bOK.Click += new EventHandler(this._Click);
this.bCancel = new Button();
this.bCancel.Parent = this;
this.bCancel.Bounds = new Rectangle (10, 50, 150, 30);
this.bCancel.Text = "Cancel";
this.bCancel.Click += new EventHandler(this._Click);
}
private void _Click(object o, EventArgs e)
{
this.Hide();
this.parent.DialogResultCallback(o == this.bOK ? DialogResult.OK : DialogResult.Cancel);
}
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
this.parent.DialogResultCallback(DialogResult.Cancel);
}
}
'VB
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Collections
Imports System.ComponentModel
Public Interface IModelessDialogCallback
Sub DialogResultCallback(result As DialogResult)
End Interface IModelessDialogCallback'
Public Class Test
Inherits System.Windows.Forms.Form
Implements IModelessDialogCallback
Private dlg As ModelessDialog
Private bShow As Button
Private counter As Integer = 0
Protected Overrides Sub OnLoad(e As EventArgs)
Me.Text = "Modal(less) Dialog Example"
Me.bShow = New Button()
Me.bShow.Parent = Me
Me.bShow.Bounds = New Rectangle(10, 10, 150, 30)
Me.bShow.Text = "Show Dialog"
AddHandler Me.bShow.Click, AddressOf Me._Click
Me.dlg = New ModelessDialog(Me)
End Sub 'OnLoad
Private Sub _Click(o As Object, e As EventArgs)
Me.Enabled = False
Me.bShow.Text = "waiting for dlg"
dlg.Show()
End Sub '_Click
Public Sub DialogResultCallback(ByVal result As DialogResult) Implements _
IModelessDialogCallback.DialogResultCallback
MessageBox.Show(("dialog returned: " + IIf(result = DialogResult.OK, "OK", "Cancel")))
Me.Enabled = True
counter += 1
Me.bShow.Text = String.Format("Show Dialog: {0}", counter)
End Sub 'DialogResultCallback
Public Shared Sub Main()
Application.Run(New Test)
End Sub 'Main
End Class 'Test
Public Class ModelessDialog
Inherits Form
Private myParent As IModelessDialogCallback
Private bOK, bCancel As Button
Public Sub New(parent As IModelessDialogCallback)
Me.myParent = parent
Me.Text = "Modeless Dialog"
Me.bOK = New Button()
Me.bOK.Parent = Me
Me.bOK.Bounds = New Rectangle(10, 10, 150, 30)
Me.bOK.Text = "OK"
AddHandler Me.bOK.Click, AddressOf Me._Click
Me.bCancel = New Button()
Me.bCancel.Parent = Me
Me.bCancel.Bounds = New Rectangle(10, 50, 150, 30)
Me.bCancel.Text = "Cancel"
AddHandler Me.bCancel.Click, AddressOf Me._Click
End Sub 'New
Private Sub _Click(o As Object, e As EventArgs)
Me.Hide()
Me.myParent.DialogResultCallback(IIf(o Is Me.bOK, DialogResult.OK, DialogResult.Cancel))
End Sub '_Click
Protected Overrides Sub OnClosing(e As CancelEventArgs)
e.Cancel = True
Me.Hide()
Me.myParent.DialogResultCallback(DialogResult.Cancel)
End Sub 'OnClosing
End Class 'ModelessDialog
Emulator | iPAQ | |||
Operation | Debug (ms) | Release (ms) | Debug (ms) | Release (ms) |
C#: Convert.ToInt32(num) | 1321 | 1109 | 6264 | 6283 |
C#: (int)(num + .5F) | 170 | 49 | 1479 | 59 |
VB: Convert.ToInt32(num) | 1218 | 1232 | 6531 | 6517 |
VB: Fix(num + .5F) | 3873 | 3677 | 18144 | 17955 |
//C#7.41. Why does Control.Invoke take so long when a modal dialog is displayed?
float temp = 3.6f;
int rounded1 = (int)(temp + .5f);
int rounded2 = Convert.ToInt32(temp);
'VB
Dim temp As Single = 3.6F
Dim rounded1 As Integer = Fix(temp + .5F)
Dim rounded2 As Integer = Convert.ToInt32(temp)
//C#
using System.Reflection;
using System.Globalization;
Assembly asm = Assembly.GetExecutingAssembly();
CultureInfo ci = asm.GetName().CultureInfo;
'VB
Imports System.Reflection
Imports System.Globalization
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim ci As CultureInfo = asm.GetName().CultureInfo
8.1. 如何通过TCP Socket向桌面机发送数据?
请查看本问答的"10.5. 写一个捕捉Pocket PC签名的程序. " 部分。
8.2. 为什么不能访问本机上的Web服务?
不要在设备上使用localhost来引用Web服务,因为对于设备来说localhost就是运行应用程序所在的设备,就是设备它本身。您应该使用机器名或IP地址来引用Web服务。
8.3. 如何在微软.net精简框架上调用Web服务
这篇文章向您演示了如何从智能设备上,通过.net精简框架同步和异步调用Web服务:
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfwebservices.asp
8.4. 如何通过代理服务器提交HTTP GET申请?
通过或不通过特定的代理服务器提交HTTP GET请求。
使用StreamReader读取返回的HTML,并转成字符数组。然后把返回的值显示在ListBox中,如以下的屏幕截图所示:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/httpgetwithproxy.aspx
8.5. 如何使用Web服务?
这篇快速入门教程,描述了如何使用提供了简单数学计算的Web服务(这个数学计算的Web服务在.net框架的快速入门中有说明,标题是"Write a Simple Web service,")。这个快速入门教程提供了一个Web服务的客户端应用:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/xmlwebservice.aspx
8.6. 如何使用MapPoint3.0得到地图?
这篇快速入门描述了如何使用MapPoint的Web服务,编程实现在PocketPC上获得特定位置的程序,如以下屏幕截图所示:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/mappointfindmap.aspx
8.7. 如何使用MapPoint3.0获得地图和方向?
这篇快速入门教程描述了如何使用MapPoint的Web服务,在PocketPC上获得特定位置的地图方向,如以下屏幕截图所示:
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/mappointdirections.aspx
8.8. Is NTLM authentication supported by the .NET Compact Framework?
Using Digest authentication instead of Basic or NTLM authentication is the recommended solution. Digest authentication is supported by the .NET Compact Framework.
8.9. When using blocking Sockets, why does Send throw an InvalidOperationException when blocking is set to false?
There is a known issue with setting Blocking to false on a blocking socket. There are three paradigms when programming with sockets (both managed and native) and it is strongly recommended that developers use asynchronous I/O functions as a solution to this problem. Select is very inefficient in managed code, and the cost of the regular case exception is also high. The three paradigms are detailed below, with the last being the preferred method.
8.10. How do I create an http-server?
Get technical insight on the implementation of Mobile Web Server architecture. Understand use cases, the web server framework and future developments in the architecture:
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/NETCFMA.asp
8.11. Why do I get an exception when calling SetSocketOption with ReuseAddress set?
This is a known issue in the version 1 of the .NET Compact Framework. To work around the issue, you can P/Invoke setsockopt with SO_REUSEADDR set to true.
8.12. Why do I get a socket error using SSL to communicate with a server via the WebRequest namespace?
There is a known issue in the .NET Compact Framework. You can work around this by setting HttpWebRequest.AllowStreamWriteBuffering to True and commenting out your setting of the ContentLength.
9.1. 使用.net精简框架、SQL Server CE 和 复制 开发应用程序时,要注意些什么?
这篇文章详细讨论了这个问题:
http://msdn.microsoft.com/msdnmag/issues/03/09/datapoints/toc.asp
9.2. 如何在微软.net精简框架上使用合并复制(Merge Replication)?
这篇文章讨论了如何通过程序在.net精简框架的应用程序中调用合并、复制:
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfmergereplication.asp
SQL Server CE是非常好的在设备上管理数据的工具,但在未复制到桌面机的SQL Server之前,它必须保留数据。使用合并、复制在设备上管理数据,然后当设备连接到桌面机时,再合并到桌面机的SQL Server的实例中。.net精简框架提供SqlCeReplication对象,可以通过程序实现数据的合并与复制。
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/sqlcemergereplication.aspx
9.3. 如何将ADO.NET数据和XML绑定?
以下三个步骤:
rda = new SqlCeRemoteDataAccess();An error of type SQLCeException with a Native Error Code of 27750 occurs. This error corresponds to "Cannot load sscemw20.dll or ssceca20.dll is missing or not registered."
SqlCeEngine eng = new SqlCeEngine();
10.1. Pocket TaskVision 程序
This document provides an overview of the development tasks that were unique to the Pocket TaskVision sample application. Pocket PC devices have much lower storage capacities, memory and lower-end processors than desktop systems—storage and performance considerations are mentioned throughout the document.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/wnf_pkttaskvision.asp
10.2. 建立基于微软.net精简框架的进程管理器
In this article, learn how to marshal structures as byte arrays.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/ProcessManager.asp
10.3. 使用微软.net精简框架开发移动游戏
Learn how to create .NET Compact Framework-based games. Learn the key requirements for writing games targeting small devices and see that the .NET Compact Framework can handle them with ease. Include advanced performance-tuning techniques that you can use to push the limits of your game.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfgaming.asp
10.4. 制作一个微软.net精简框架的DateTimePicker控件
Learn how to use a managed DateTimePicker class in your Pocket PC projects. The .net精简框架 provides managed classes for most controls but the DateTimePicker class is not supported. Wrapper classes that P/Invoke the native control can be found on the Web, but this sample provides a purely managed DateTimePicker class that you can use in your Pocket PC projects. The class and sample application are provided in C# and Visual Basic .NET.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/netcfdatetimepicker.asp
10.5. 写一个捕捉Pocket PC签名的程序.
This article discusses the Pocket PC Signature sample application. The sample includes a client that runs on the Pocket PC that sends signature data over TCP sockets to a server that is running on the desktop. Data is encrypted and decrypted using the cryptography services.
http://msdn.microsoft.com/library/en-us/dnnetcomp/html/PPCSignatureApp.asp
10.6. 有没有非微软的网站提供在.net精简框架上开发应用的信息?
See the "Related Sites" section of the MSDN Mobile and Embedded Developer Center:
http://msdn.microsoft.com/mobility/Community/related/default.aspx
11.1. 为什么不同通过ActiveSync把程序部署到Windows CE的设备上?
Symptom: When a Windows CE device is connected through ActiveSync, deployment and debugging (F5 and Ctrl-F5) fail with the typical error message "There were deployment errors. Continue?"
Cause: Due to the fact that ActiveSync 3.5 and 3.6 do not provide accurate information about the device instruction set, ConMan (Visual Studio .NET 2003 component for device connectivity) cannot use the information returned by ActiveSync to map a Windows CE device to the right .NET Compact Framework target (MIPSII, ARMV4 etc).
Workaround: Install and run the separately provided Windows CE Configuration Add-In. For ARMV4 devices, an alternative is to select Pocket PC Device at the beginning of the deployment.
11.2. 为什么不能通过ActiveSync调试 CEPC 或其他 x86 的Windows CE设备?
Symptom: After running the Windows CE Device Configuration Add-In, the user can deploy without debugging (Ctrl-F5) to an ActiveSync connected CEPC (or any x86 based Windows CE device) but cannot debug (F5). Non-x86 based Windows CE devices do not have this problem.
Cause: Debugging Windows CE Emulators (also x86 based) uses a TCP port that conflicts with the one used by ActiveSync for debugging x86 based devices. To support Emulator debugging, it is necessary to disable debugging for CEPC and other x86 devices by default.
Workaround: The following workaround will allow debugging of x86 devices but disable debugging with the Windows CE Emulator. The workaround requires the files WinCEx86Device.reg, and ProxyPorts.reg which can be found in the SDK utilities directory: "<VSROOT>/CompactFrameworkSDK/WinCE Utilities/WinCE Proxy Ports Reg".
If you do not have these files they can be downloaded from the following link:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7ec99ca6-2095-4086-b0cc-7c6c39b28762&DisplayLang=en#filelist
12.1. Where can I get the latest Smartphone SDK?
Download the Windows Mobile 2003 Smartphone SDK here:
http://www.microsoft.com/downloads/details.aspx?familyid=a6c4f799-ec5c-427c-807c-4c0f96765a81&displaylang=en
12.2. What are the rules for smartphone menus?
Smartphone menus have several rules, such as:
'VB
Imports System.Runtime.InteropServices
Public Const EM_SETINPUTMODE As Integer = &HDE
Public Const EIM_SPELL As Integer = 0
Public Const EIM_AMBIG As Integer = 1
Public Const EIM_NUMBERS As Integer = 2
<DllImport("coredll.dll")> _
Public Shared Function GetFocus() As IntPtr
End Function
<DllImport("coredll.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Message As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer
End Function
'Sample use setting TextBox to number input
Private Sub txtAmount_GotFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtAmount.GotFocus
Dim hWnd As IntPtr
hWnd = Me.GetFocus()
SendMessage(hWnd, EM_SETINPUTMODE, 0, EIM_NUMBERS)
txtAmount.SelectionStart = txtAmount.Text.Length
End Sub
//C#
using System.Runtime.InteropServices;
public const uint EM_SETINPUTMODE = 0xDE;
public const uint EIM_SPELL = 0;
public const uint EIM_AMBIG = 1;
public const uint EIM_NUMBERS = 2;
[DllImport("coredll.dll")]
public static extern IntPtr GetFocus();
[DllImport("coredll.dll")]
public static extern int SendMessage(IntPtr hWnd,
uint Message, uint wParam, uint lParam);
// Sample use setting TextBox to number input
private void Form1_Load(object sender, System.EventArgs e)
{
txtAmount.GotFocus +=
new System.EventHandler(txtAmount_GotFocus);
}
private void txtAmount_GotFocus(object sender, System.EventArgs e)
{
IntPtr hWnd;
hWnd = GetFocus();
SendMessage(hWnd, EM_SETINPUTMODE, 0, EIM_NUMBERS);
txtAmount.SelectionStart = txtAmount.Text.Length;
}