每周源代码45-Windows 7和Windows XP上的踢屁股

I really advocate folks reading as much source as they can because you become a better writer by reading as much as writing. That's the whole point of the Weekly Source Code - reading code to be a better developer.

我真的提倡人们阅读尽可能多的资料,因为您会通过阅读和写作而成为更好的作家。 这就是每周源代码的重点-阅读代码以成为一名更好的开发人员。

There's a very cool developer context going on right now called "Code7." If you code a Windows 7 application between now and October 7 you could win a giant bag of money and/or a trip to PDC.

现在有一个非常酷的开发人员上下文称为“ Code7” 。 如果您在现在到10月7日之间编写Windows 7应用程序代码,则可能会赢得一大笔钱和/或去PDC。

There's a pile of new APIs in Windows 7 (as well as existing and useful Vista APIs) like these:

Windows 7中许多新的API (以及现有的和有用的Vista API),如下所示:

  • Windows 7 Taskbar Integration

    Windows 7任务栏集成
  • Transactional File System

    交易文件系统
  • I/O Optimization

    I / O优化
  • Event Tracing for Windows (ETW)

    Windows事件跟踪(ETW)
  • Windows 7 Libraries

    Windows 7库
  • Windows 7 Sensor and Location Platform

    Windows 7传感器和定位平台
  • Aero Glass

    航空玻璃

In some of these instances, there isn't hardware (yet) for things like Ambient Light Sensors. One dude has taken a Webcam and hooked it into the Windows 7 Sensors API and made a program to dim his monitors with the new Monitor Configuration API*. He might even make it turn off his machine when he walks away.

在某些情况下,还没有诸如环境光传感器之类的硬件。 一个家伙花了一个摄像头,将其连接到Windows 7 Sensors API中,并制作了一个程序,使用新的Monitor Configuration API *对其显示器进行调光。 他走开时甚至可能关闭机器。

XP2Win7 -Windows 7示例代码/应用程序 (XP2Win7 - Windows 7 Sample Code/Application)

I've been checking out what sample applications there are to start learning about Windows 7. The coolest so far as been the "PhotoView" application. Don't sweat the fact it's YAPA (Yet Another Photo Application) and consider it a loosely confederated collection of samples.

我一直在研究有哪些示例应用程序可以开始学习Windows7。到目前为止,最酷的是“ PhotoView”应用程序。 不要大惊小怪,它是YAPA(又是另一张照片应用程序),并认为它是松散联盟的样本集合。

MainWindow

What's cool about this application is that it works on Windows XP and Windows Vista and Windows 7. This may be obvious and even a silly statement to you, Dear Reader, but it's a nice reminder that and app can be awesome on all three platforms. 99% of the apps that I use work great on Windows 7. Sure, some drivers and wacky VPN things will need to be updated, but it's comforting to me to know I can write an app for Windows that will, um, work on Windows. ;)

该应用程序最酷的地方是它可以在Windows XP,Windows Vista和Windows 7上运行。 亲爱的读者,这对您来说可能很明显,甚至是一个愚蠢的声明,但很高兴地提醒您,在三个平台上,and app都很棒。 我使用的应用程序中的99%可以在Windows 7上很好地运行。当然,某些驱动程序和古怪的VPN东西需要进行更新,但是让我感到欣慰的是,我可以为Windows编写可以在Windows上运行的应用程序。 ;)

This PhotoView application, also called XP2Win7 is written managed code and uses plugins to "light up on up-level platforms." That's fancy Microsoft talk that means if your operating system has a feature the app will detect it and use it.

这个PhotoView应用程序也称为XP2Win7,是编写的托管代码,并使用插件“在高级平台上点亮”。 微软的话很花哨,这意味着如果您的操作系统具有某个功能,则该应用将检测到并使用它。

There's a great overview Word Document that explains the app and how it is written. The MSI will install the app, then optionally the source in ~\MyDocuments\Xp2Win7 if you have trouble finding it. You'll need Visual C++ if you want to build a few parts...just read the readme. It's a pretty extraordinarily broad sample with examples on how to make MMC ReportViewer snapins, delayed services, register scheduled tasks, piles.

有一个很好的概述Word Document,它解释了该应用程序及其编写方式。 MSI将安装该应用程序,如果找不到它,则可以选择安装〜\ MyDocuments \ Xp2Win7中的源。 如果要构建一些部分,则需要Visual C ++。只需阅读自述文件。 这是一个非常广泛的示例,其中包含有关如何制作MMC ReportViewer管理单元,延迟服务,注册计划任务,堆的示例。

(Unfortunately the guys that wrote this didn't use MEF for their plugin model, but I'll talk to them. It would allow them to remove a lot of boilerplate plugin monkey code.)

(不幸的是,编写此代码的人并未在他们的插件模型中使用MEF ,但我会与他们交谈。这将使他们删除许多样板插件猴子代码。)

It uses the Windows API Code Pack (I talk about this below) to do a lot of its work. Here's a few fun parts.

它使用Windows API代码包(我将在下面讨论)完成许多工作。 这里有一些有趣的部分。

任务栏跳转列表 (TaskBar JumpLists)

When the app is run under Windows 7 it includes "jumplists" when you right-click (or swipe-up) on the taskbar button:

在Windows 7下运行该应用程序时,在任务栏按钮上单击鼠标右键(或向上滑动)时,它会包含“ jumplists”:

This is easily added with the Taskbar API. Notice the multiple categories, user tasks, recent items, and custom categories.

可通过任务栏API轻松添加。 请注意多个类别,用户任务,近期项目和自定义类别。

Taskbar.JumpList.CustomCategories.Clear();
Taskbar.JumpList.UserTasks.Clear();
Taskbar.JumpList.KnownCategoryToDisplay = KnownCategoryType.Recent;

CustomCategory allAlbumsCategory = new CustomCategory("All Albums");
//...snip out enumerating of the filesystem to get photo albums
Taskbar.JumpList.CustomCategories.Add(allAlbumsCategory);

Taskbar.JumpList.UserTasks.Add(
new JumpListLink()
{
Title = "Reset configuration",
Path = typeof(XP2Win7.VistaPlugins.ConfigurationResetter.Program).Assembly.Location,
Arguments = XP2Win7.VistaPlugins.ConfigurationResetter.Program.ResetCommand
});
Taskbar.JumpList.UserTasks.Add(
new JumpListLink
{
Title = "Launch indexing task",
Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Constants.ServiceCommandLine),
Arguments = Constants.ServiceAsTaskCommandLine
});
Taskbar.JumpList.UserTasks.Add(
new JumpListLink { Title = "Open albums directory", Path = Host.UserConfiguration.AlbumRepositoryPath });

Taskbar.JumpList.RefreshTaskbarList();
Windows 7库 (Windows 7 Libraries)

You can also add Windows 7 Libraries for your application:

您还可以为应用程序添加Windows 7库:

//Create new shell library under the default Libraries
using (ShellLibrary library = new ShellLibrary("XP2Win7", true))
{
library.LibraryType = LibraryFolderType.Pictures;
library.IconResourceId = GetPictureLibraryIcon(); //Set the same Icon as the Picture library
library.IsPinnedToNavigationPane = true;


foreach (string folderPath in GetPicturesFolders())
{
library.Add(folderPath);
}

library.ShowManageLibraryUI(Application.Current.MainWindow,
"Manage the XP2Win7 library", "You can manualy add or remove folders",
true);
}
用户访问控制(UAC) (User Access Control (UAC))

Windows Vista and Windows 7 both include User Access Control (UAC). You'll recognize the little shield icon next to a button that will require a prompt from the user in the dialog below.

Windows Vista和Windows 7均包含用户访问控制(UAC)。 您会在按钮旁边看到一个小的盾牌图标,该图标要求用户在下面的对话框中进行提示。

Application reconfiguration

Their application uses this in a few places. First, can we even show the little shield? We only want to do that if UAC is enabled:

他们的应用程序在一些地方使用了它。 首先,我们什至可以显示小盾牌吗? 我们只想在启用UAC的情况下这样做:

protected override BitmapSource BitmapSource
{
get
{
if (UacHelpers.UserAccountControl.IsUacEnabled)
{
return Microsoft.SDK.Samples.VistaBridge.Library.StockIcons.StockIcons.Shield;
}
else
{
return ImageFromResource(Assembly.GetExecutingAssembly(),
"UserAccountControl.StartService-128x128.png");
}
}
}

Then, if they do click the button, and we want to launch some process as Administrator, we'll need to call a special API to do that. This is mean easy by helper APIs.

然后,如果他们确实单击了按钮,并且我们想以管理员身份启动某些过程,则需要调用特殊的API来执行此操作。 通过助手API可以轻松实现。

if (UacHelpers.UserAccountControl.IsUacEnabled || !UacHelpers.UserAccountControl.IsUserAdmin)
{
UacHelpers.UserAccountControl.CreateProcessAsAdmin(
typeof(ServiceStarter.Program).Assembly.Location, "XP2Win7ImageDataService");
}
else
{
Process.Start(typeof(ServiceStarter.Program).Assembly.Location, "XP2Win7ImageDataService");
}

Pretty slick and easy to code. The Windows API Code Pack makes all these APIs and dozens more easy for managed code developers (C#, VB, and everyone else.)

非常光滑,易于编码。 Windows API代码包使所有这些API以及托管代码开发人员(C#,VB和其他所有人)都更容易使用。

Windows API代码包 (Windows API Code Pack)

Another great pile of Windows sample code is the Windows API Code Pack. This thing is a gold mine of samples and they are all in C# and VB. There's like 20+ samples. Here's a few:

Windows示例代码的另一堆是Windows API代码包这个东西是样本的金矿它们都在C#和VB中。 大约有20多个样本。 这里有一些:

能源管理 (Power Management )

It's nice if your app knows the power status of the machine it's on and avoid doing crazy stuff if it's on batteries.

如果您的应用知道正在运行的机器的电源状态,并且如果用电池供电,请避免做疯狂的事情,这很好。

Power Management

You can get all sorts of great power-related info:

您可以获得各种与功率相关的信息:

private void GetPowerSettings()
{
settings.PowerPersonality = PowerManager.PowerPersonality.ToString();
settings.PowerSource = PowerManager.PowerSource.ToString();
settings.BatteryPresent = PowerManager.IsBatteryPresent;
settings.UpsPresent = PowerManager.IsUpsPresent;
settings.MonitorOn = PowerManager.IsMonitorOn;
settings.MonitorRequired = PowerManager.MonitorRequired;

if (PowerManager.IsBatteryPresent)
{
settings.BatteryShortTerm = PowerManager.IsBatteryShortTerm;
settings.BatteryLifePercent = PowerManager.BatteryLifePercent;

BatteryState batteryState = PowerManager.GetCurrentBatteryState();

string batteryStateStr = string.Format(
"ACOnline: {1}{0}Max Charge: {2} mWh{0}Current Charge: {3} mWh{0}Discharge Rate: {4} {0}Estimated Time Remaining: {5}{0}Suggested Critical Battery Charge: {6} mWh{0}Suggested Battery Warning Charge: {7} mWh{0}",
Environment.NewLine,
batteryState.ACOnline,
batteryState.MaxCharge,
batteryState.CurrentCharge,
batteryState.ACOnline == true ? "N/A" : batteryState.DischargeRate.ToString() + " mWh",
batteryState.ACOnline == true ? "N/A" : batteryState.EstimatedTimeRemaining.ToString(),
batteryState.SuggestedCriticalBatteryCharge,
batteryState.SuggestedBatteryWarningCharge
);

settings.BatteryState = batteryStateStr;
}
}

There's also lots of power-related events you can be notified of:

您还会收到许多与电源有关的事件的通知:

PowerManager.IsMonitorOnChanged += new EventHandler(MonitorOnChanged);
PowerManager.PowerPersonalityChanged += new EventHandler(
PowerPersonalityChanged);
PowerManager.PowerSourceChanged += new EventHandler(PowerSourceChanged);
if (PowerManager.IsBatteryPresent)
{
PowerManager.BatteryLifePercentChanged += new EventHandler(BatteryLifePercentChanged);

// Set the label for the battery life
SetLabelButtonStatus(batteryLifePercentLabel, string.Format("{0}%", PowerManager.BatteryLifePercent.ToString()));
}

PowerManager.SystemBusyChanged += new EventHandler(SystemBusyChanged);
股票图标 (Stock Icons)

A lot of folks don't realize that there's a pile of stock icons that are available in Windows and you can access them programmatically.

许多人没有意识到Windows中有大量可用的库存图标,您可以通过编程方式访问它们。

 

That means if you need the stock icon for a BluRayRom or a ZipFile, you can just ask for it.

这意味着,如果您需要用于BluRayRom或ZipFile的股票图标,则可以要求它。

任务栏进度 (Task Bar Progress)

One of the nicest subtle features of Win7 is that if you've got a Progress Bar doing something in your application you can make its progress known in the Taskbar icon itself. This is fantastic for long-running processes like file copies, etc.

Win7最好的微妙功能之一就是,如果您在应用程序中有一个进度条,您可以在任务栏图标本身中显示其进度。 这对于长时间运行的进程(如文件副本等)来说非常理想。

Notice the progress bar in this application and the taskbar button in the bottom right reflects it.

注意此应用程序中的进度条,右下角的任务栏按钮将其反映出来。

There's also icon/image overlays and other nice touches. Even better, this is epic-easy:

还有图标/图像覆盖和其他漂亮的感觉。 更好的是,这很容易:

// When the user changes the trackBar value,
// update the progress bar in our UI as well as Taskbar
progressBar1.Value = trackBar1.Value;

TaskbarManager.Instance.SetProgressValue(trackBar1.Value, 100);

Since your app can have multiple progress bars, you have to manually decide what you want the taskbar progress to look like.

由于您的应用程序可以具有多个进度条,因此您必须手动确定任务栏进度的外观。

核心帮手 (Core Helpers)

Finally there's some nice "CoreHelpers" to make your applications easy to read and run on XP, Vista and Win7 at the same time:

最后,有一些不错的“ CoreHelpers”使您的应用程序易于阅读,并且可以同时在XP,Vista和Win7上运行:

//example
if (CoreHelpers.RunningOnXP()) { ... }
//example
if (CoreHelpers.ThrowifNotWin7() { ... }
// and all the others you'd expect for XP, Vista, Win7

I've just touched the surface of these samples. If you're doing Windowe Client development be sure to check out http://windowsclient.net/ and http://www.msdn.com/windows for more and start writing your application for the https://www.code7contest.com.

我刚刚摸过这些样品的表面。 如果您正在进行Windowe Client开发,请确保查看http://windowsclient.net/http://www.msdn.com/windows了解更多信息,然后开始为https://www.code7contest编写应用程序。 com

1. Get Windows 7 and the SDK

1.获取Windows 7和SDK

2. Develop and Test Your Application

2.开发和测试您的应用程序

3. Get the Windows 7 Logo

3.获取Windows 7徽标

4. Light Up Your Application with Windows 7

4.使用Windows 7点亮您的应用程序

Related Links

相关链接

* Note the (lightweight) parameter I passed into this MSDN URL. Check out the new "Lightweight" MSDN Library and give the team feedback on the site!

*请注意我传递给此MSDN URL的(lightweight)参数。 查看新的“轻量级” MSDN库,并在网站上为团队提供反馈

翻译自: https://www.hanselman.com/blog/the-weekly-source-code-45-kicking-butt-on-windows-7-and-windows-xp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值